accountcmd.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. "os"
  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. "github.com/urfave/cli/v2"
  26. )
  27. var (
  28. walletCommand = &cli.Command{
  29. Name: "wallet",
  30. Usage: "Manage Ethereum presale wallets",
  31. ArgsUsage: "",
  32. Description: `
  33. geth wallet import /path/to/my/presale.wallet
  34. will prompt for your password and imports your ether presale account.
  35. It can be used non-interactively with the --password option taking a
  36. passwordfile as argument containing the wallet password in plaintext.`,
  37. Subcommands: []*cli.Command{
  38. {
  39. Name: "import",
  40. Usage: "Import Ethereum presale wallet",
  41. ArgsUsage: "<keyFile>",
  42. Action: importWallet,
  43. Flags: []cli.Flag{
  44. utils.DataDirFlag,
  45. utils.KeyStoreDirFlag,
  46. utils.PasswordFileFlag,
  47. utils.LightKDFFlag,
  48. },
  49. Description: `
  50. geth wallet [options] /path/to/my/presale.wallet
  51. will prompt for your password and imports your ether presale account.
  52. It can be used non-interactively with the --password option taking a
  53. passwordfile as argument containing the wallet password in plaintext.`,
  54. },
  55. },
  56. }
  57. accountCommand = &cli.Command{
  58. Name: "account",
  59. Usage: "Manage accounts",
  60. Description: `
  61. Manage accounts, list all existing accounts, import a private key into a new
  62. account, create a new account or update an existing account.
  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. Subcommands: []*cli.Command{
  75. {
  76. Name: "list",
  77. Usage: "Print summary of existing accounts",
  78. Action: accountList,
  79. Flags: []cli.Flag{
  80. utils.DataDirFlag,
  81. utils.KeyStoreDirFlag,
  82. },
  83. Description: `
  84. Print a short summary of all accounts`,
  85. },
  86. {
  87. Name: "new",
  88. Usage: "Create a new account",
  89. Action: accountCreate,
  90. Flags: []cli.Flag{
  91. utils.DataDirFlag,
  92. utils.KeyStoreDirFlag,
  93. utils.PasswordFileFlag,
  94. utils.LightKDFFlag,
  95. },
  96. Description: `
  97. geth account new
  98. Creates a new account and prints the address.
  99. The account is saved in encrypted format, you are prompted for a password.
  100. You must remember this password to unlock your account in the future.
  101. For non-interactive use the password can be specified with the --password flag:
  102. Note, this is meant to be used for testing only, it is a bad idea to save your
  103. password to file or expose in any other way.
  104. `,
  105. },
  106. {
  107. Name: "update",
  108. Usage: "Update an existing account",
  109. Action: accountUpdate,
  110. ArgsUsage: "<address>",
  111. Flags: []cli.Flag{
  112. utils.DataDirFlag,
  113. utils.KeyStoreDirFlag,
  114. utils.LightKDFFlag,
  115. },
  116. Description: `
  117. geth account update <address>
  118. Update an existing account.
  119. The account is saved in the newest version in encrypted format, you are prompted
  120. for a password to unlock the account and another to save the updated file.
  121. This same command can therefore be used to migrate an account of a deprecated
  122. format to the newest format or change the password for an account.
  123. For non-interactive use the password can be specified with the --password flag:
  124. geth account update [options] <address>
  125. Since only one password can be given, only format update can be performed,
  126. changing your password is only possible interactively.
  127. `,
  128. },
  129. {
  130. Name: "import",
  131. Usage: "Import a private key into a new account",
  132. Action: accountImport,
  133. Flags: []cli.Flag{
  134. utils.DataDirFlag,
  135. utils.KeyStoreDirFlag,
  136. utils.PasswordFileFlag,
  137. utils.LightKDFFlag,
  138. },
  139. ArgsUsage: "<keyFile>",
  140. Description: `
  141. geth account import <keyfile>
  142. Imports an unencrypted private key from <keyfile> and creates a new account.
  143. Prints the address.
  144. The keyfile is assumed to contain an unencrypted private key in hexadecimal format.
  145. The account is saved in encrypted format, you are prompted for a password.
  146. You must remember this password to unlock your account in the future.
  147. For non-interactive use the password can be specified with the -password flag:
  148. geth account import [options] <keyfile>
  149. Note:
  150. As you can directly copy your encrypted accounts to another ethereum instance,
  151. this import mechanism is not needed when you transfer an account between
  152. nodes.
  153. `,
  154. },
  155. },
  156. }
  157. )
  158. func accountList(ctx *cli.Context) error {
  159. stack, _ := makeConfigNode(ctx)
  160. var index int
  161. for _, wallet := range stack.AccountManager().Wallets() {
  162. for _, account := range wallet.Accounts() {
  163. fmt.Printf("Account #%d: {%x} %s\n", index, account.Address, &account.URL)
  164. index++
  165. }
  166. }
  167. return nil
  168. }
  169. // tries unlocking the specified account a few times.
  170. func unlockAccount(ks *keystore.KeyStore, address string, i int, passwords []string) (accounts.Account, string) {
  171. account, err := utils.MakeAddress(ks, address)
  172. if err != nil {
  173. utils.Fatalf("Could not list accounts: %v", err)
  174. }
  175. for trials := 0; trials < 3; trials++ {
  176. prompt := fmt.Sprintf("Unlocking account %s | Attempt %d/%d", address, trials+1, 3)
  177. password := utils.GetPassPhraseWithList(prompt, false, i, passwords)
  178. err = ks.Unlock(account, password)
  179. if err == nil {
  180. log.Info("Unlocked account", "address", account.Address.Hex())
  181. return account, password
  182. }
  183. if err, ok := err.(*keystore.AmbiguousAddrError); ok {
  184. log.Info("Unlocked account", "address", account.Address.Hex())
  185. return ambiguousAddrRecovery(ks, err, password), password
  186. }
  187. if err != keystore.ErrDecrypt {
  188. // No need to prompt again if the error is not decryption-related.
  189. break
  190. }
  191. }
  192. // All trials expended to unlock account, bail out
  193. utils.Fatalf("Failed to unlock account %s (%v)", address, err)
  194. return accounts.Account{}, ""
  195. }
  196. func ambiguousAddrRecovery(ks *keystore.KeyStore, err *keystore.AmbiguousAddrError, auth string) accounts.Account {
  197. fmt.Printf("Multiple key files exist for address %x:\n", err.Addr)
  198. for _, a := range err.Matches {
  199. fmt.Println(" ", a.URL)
  200. }
  201. fmt.Println("Testing your password against all of them...")
  202. var match *accounts.Account
  203. for i, a := range err.Matches {
  204. if e := ks.Unlock(a, auth); e == nil {
  205. match = &err.Matches[i]
  206. break
  207. }
  208. }
  209. if match == nil {
  210. utils.Fatalf("None of the listed files could be unlocked.")
  211. return accounts.Account{}
  212. }
  213. fmt.Printf("Your password unlocked %s\n", match.URL)
  214. fmt.Println("In order to avoid this warning, you need to remove the following duplicate key files:")
  215. for _, a := range err.Matches {
  216. if a != *match {
  217. fmt.Println(" ", a.URL)
  218. }
  219. }
  220. return *match
  221. }
  222. // accountCreate creates a new account into the keystore defined by the CLI flags.
  223. func accountCreate(ctx *cli.Context) error {
  224. cfg := gethConfig{Node: defaultNodeConfig()}
  225. // Load config file.
  226. if file := ctx.String(configFileFlag.Name); file != "" {
  227. if err := loadConfig(file, &cfg); err != nil {
  228. utils.Fatalf("%v", err)
  229. }
  230. }
  231. utils.SetNodeConfig(ctx, &cfg.Node)
  232. keydir, err := cfg.Node.KeyDirConfig()
  233. if err != nil {
  234. utils.Fatalf("Failed to read configuration: %v", err)
  235. }
  236. scryptN := keystore.StandardScryptN
  237. scryptP := keystore.StandardScryptP
  238. if cfg.Node.UseLightweightKDF {
  239. scryptN = keystore.LightScryptN
  240. scryptP = keystore.LightScryptP
  241. }
  242. 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))
  243. account, err := keystore.StoreKey(keydir, password, scryptN, scryptP)
  244. if err != nil {
  245. utils.Fatalf("Failed to create account: %v", err)
  246. }
  247. fmt.Printf("\nYour new key was generated\n\n")
  248. fmt.Printf("Public address of the key: %s\n", account.Address.Hex())
  249. fmt.Printf("Path of the secret key file: %s\n\n", account.URL.Path)
  250. fmt.Printf("- You can share your public address with anyone. Others need it to interact with you.\n")
  251. fmt.Printf("- You must NEVER share the secret key with anyone! The key controls access to your funds!\n")
  252. fmt.Printf("- You must BACKUP your key file! Without the key, it's impossible to access account funds!\n")
  253. fmt.Printf("- You must REMEMBER your password! Without the password, it's impossible to decrypt the key!\n\n")
  254. return nil
  255. }
  256. // accountUpdate transitions an account from a previous format to the current
  257. // one, also providing the possibility to change the pass-phrase.
  258. func accountUpdate(ctx *cli.Context) error {
  259. if ctx.Args().Len() == 0 {
  260. utils.Fatalf("No accounts specified to update")
  261. }
  262. stack, _ := makeConfigNode(ctx)
  263. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  264. for _, addr := range ctx.Args().Slice() {
  265. account, oldPassword := unlockAccount(ks, addr, 0, nil)
  266. newPassword := utils.GetPassPhraseWithList("Please give a new password. Do not forget this password.", true, 0, nil)
  267. if err := ks.Update(account, oldPassword, newPassword); err != nil {
  268. utils.Fatalf("Could not update the account: %v", err)
  269. }
  270. }
  271. return nil
  272. }
  273. func importWallet(ctx *cli.Context) error {
  274. if ctx.Args().Len() != 1 {
  275. utils.Fatalf("keyfile must be given as the only argument")
  276. }
  277. keyfile := ctx.Args().First()
  278. keyJSON, err := os.ReadFile(keyfile)
  279. if err != nil {
  280. utils.Fatalf("Could not read wallet file: %v", err)
  281. }
  282. stack, _ := makeConfigNode(ctx)
  283. passphrase := utils.GetPassPhraseWithList("", false, 0, utils.MakePasswordList(ctx))
  284. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  285. acct, err := ks.ImportPreSaleKey(keyJSON, passphrase)
  286. if err != nil {
  287. utils.Fatalf("%v", err)
  288. }
  289. fmt.Printf("Address: {%x}\n", acct.Address)
  290. return nil
  291. }
  292. func accountImport(ctx *cli.Context) error {
  293. if ctx.Args().Len() != 1 {
  294. utils.Fatalf("keyfile must be given as the only argument")
  295. }
  296. keyfile := ctx.Args().First()
  297. key, err := crypto.LoadECDSA(keyfile)
  298. if err != nil {
  299. utils.Fatalf("Failed to load the private key: %v", err)
  300. }
  301. stack, _ := makeConfigNode(ctx)
  302. 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))
  303. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  304. acct, err := ks.ImportECDSA(key, passphrase)
  305. if err != nil {
  306. utils.Fatalf("Could not create the account: %v", err)
  307. }
  308. fmt.Printf("Address: {%x}\n", acct.Address)
  309. return nil
  310. }