github.com/linapex/ethereum-go-chinese@v0.0.0-20190316121929-f8b7a73c3fa1/cmd/geth/accountcmd.go (about)

     1  
     2  //<developer>
     3  //    <name>linapex 曹一峰</name>
     4  //    <email>linapex@163.com</email>
     5  //    <wx>superexc</wx>
     6  //    <qqgroup>128148617</qqgroup>
     7  //    <url>https://jsq.ink</url>
     8  //    <role>pku engineer</role>
     9  //    <date>2019-03-16 19:16:32</date>
    10  //</624450068191121408>
    11  
    12  
    13  package main
    14  
    15  import (
    16  	"fmt"
    17  	"io/ioutil"
    18  
    19  	"github.com/ethereum/go-ethereum/accounts"
    20  	"github.com/ethereum/go-ethereum/accounts/keystore"
    21  	"github.com/ethereum/go-ethereum/cmd/utils"
    22  	"github.com/ethereum/go-ethereum/console"
    23  	"github.com/ethereum/go-ethereum/crypto"
    24  	"github.com/ethereum/go-ethereum/log"
    25  	"gopkg.in/urfave/cli.v1"
    26  )
    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  
    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  		Subcommands: []cli.Command{
    41  			{
    42  
    43  				Name:      "import",
    44  				Usage:     "Import Ethereum presale wallet",
    45  				ArgsUsage: "<keyFile>",
    46  				Action:    utils.MigrateFlags(importWallet),
    47  				Category:  "ACCOUNT COMMANDS",
    48  				Flags: []cli.Flag{
    49  					utils.DataDirFlag,
    50  					utils.KeyStoreDirFlag,
    51  					utils.PasswordFileFlag,
    52  					utils.LightKDFFlag,
    53  				},
    54  				Description: `
    55  	geth wallet [options] /path/to/my/presale.wallet
    56  
    57  will prompt for your password and imports your ether presale account.
    58  It can be used non-interactively with the --password option taking a
    59  passwordfile as argument containing the wallet password in plaintext.`,
    60  			},
    61  		},
    62  	}
    63  
    64  	accountCommand = cli.Command{
    65  		Name:     "account",
    66  		Usage:    "Manage accounts",
    67  		Category: "ACCOUNT COMMANDS",
    68  		Description: `
    69  
    70  Manage accounts, list all existing accounts, import a private key into a new
    71  account, create a new account or update an existing account.
    72  
    73  It supports interactive mode, when you are prompted for password as well as
    74  non-interactive mode where passwords are supplied via a given password file.
    75  Non-interactive mode is only meant for scripted use on test networks or known
    76  safe environments.
    77  
    78  Make sure you remember the password you gave when creating a new account (with
    79  either new or import). Without it you are not able to unlock your account.
    80  
    81  Note that exporting your key in unencrypted format is NOT supported.
    82  
    83  Keys are stored under <DATADIR>/keystore.
    84  It is safe to transfer the entire directory or the individual keys therein
    85  between ethereum nodes by simply copying.
    86  
    87  Make sure you backup your keys regularly.`,
    88  		Subcommands: []cli.Command{
    89  			{
    90  				Name:   "list",
    91  				Usage:  "Print summary of existing accounts",
    92  				Action: utils.MigrateFlags(accountList),
    93  				Flags: []cli.Flag{
    94  					utils.DataDirFlag,
    95  					utils.KeyStoreDirFlag,
    96  				},
    97  				Description: `
    98  Print a short summary of all accounts`,
    99  			},
   100  			{
   101  				Name:   "new",
   102  				Usage:  "Create a new account",
   103  				Action: utils.MigrateFlags(accountCreate),
   104  				Flags: []cli.Flag{
   105  					utils.DataDirFlag,
   106  					utils.KeyStoreDirFlag,
   107  					utils.PasswordFileFlag,
   108  					utils.LightKDFFlag,
   109  				},
   110  				Description: `
   111      geth account new
   112  
   113  Creates a new account and prints the address.
   114  
   115  The account is saved in encrypted format, you are prompted for a passphrase.
   116  
   117  You must remember this passphrase to unlock your account in the future.
   118  
   119  For non-interactive use the passphrase can be specified with the --password flag:
   120  
   121  Note, this is meant to be used for testing only, it is a bad idea to save your
   122  password to file or expose in any other way.
   123  `,
   124  			},
   125  			{
   126  				Name:      "update",
   127  				Usage:     "Update an existing account",
   128  				Action:    utils.MigrateFlags(accountUpdate),
   129  				ArgsUsage: "<address>",
   130  				Flags: []cli.Flag{
   131  					utils.DataDirFlag,
   132  					utils.KeyStoreDirFlag,
   133  					utils.LightKDFFlag,
   134  				},
   135  				Description: `
   136      geth account update <address>
   137  
   138  Update an existing account.
   139  
   140  The account is saved in the newest version in encrypted format, you are prompted
   141  for a passphrase to unlock the account and another to save the updated file.
   142  
   143  This same command can therefore be used to migrate an account of a deprecated
   144  format to the newest format or change the password for an account.
   145  
   146  For non-interactive use the passphrase can be specified with the --password flag:
   147  
   148      geth account update [options] <address>
   149  
   150  Since only one password can be given, only format update can be performed,
   151  changing your password is only possible interactively.
   152  `,
   153  			},
   154  			{
   155  				Name:   "import",
   156  				Usage:  "Import a private key into a new account",
   157  				Action: utils.MigrateFlags(accountImport),
   158  				Flags: []cli.Flag{
   159  					utils.DataDirFlag,
   160  					utils.KeyStoreDirFlag,
   161  					utils.PasswordFileFlag,
   162  					utils.LightKDFFlag,
   163  				},
   164  				ArgsUsage: "<keyFile>",
   165  				Description: `
   166      geth account import <keyfile>
   167  
   168  Imports an unencrypted private key from <keyfile> and creates a new account.
   169  Prints the address.
   170  
   171  The keyfile is assumed to contain an unencrypted private key in hexadecimal format.
   172  
   173  The account is saved in encrypted format, you are prompted for a passphrase.
   174  
   175  You must remember this passphrase to unlock your account in the future.
   176  
   177  For non-interactive use the passphrase can be specified with the -password flag:
   178  
   179      geth account import [options] <keyfile>
   180  
   181  Note:
   182  As you can directly copy your encrypted accounts to another ethereum instance,
   183  this import mechanism is not needed when you transfer an account between
   184  nodes.
   185  `,
   186  			},
   187  		},
   188  	}
   189  )
   190  
   191  func accountList(ctx *cli.Context) error {
   192  	stack, _ := makeConfigNode(ctx)
   193  	var index int
   194  	for _, wallet := range stack.AccountManager().Wallets() {
   195  		for _, account := range wallet.Accounts() {
   196  			fmt.Printf("Account #%d: {%x} %s\n", index, account.Address, &account.URL)
   197  			index++
   198  		}
   199  	}
   200  	return nil
   201  }
   202  
   203  //尝试解锁指定帐户几次。
   204  func unlockAccount(ctx *cli.Context, ks *keystore.KeyStore, address string, i int, passwords []string) (accounts.Account, string) {
   205  	account, err := utils.MakeAddress(ks, address)
   206  	if err != nil {
   207  		utils.Fatalf("Could not list accounts: %v", err)
   208  	}
   209  	for trials := 0; trials < 3; trials++ {
   210  		prompt := fmt.Sprintf("Unlocking account %s | Attempt %d/%d", address, trials+1, 3)
   211  		password := getPassPhrase(prompt, false, i, passwords)
   212  		err = ks.Unlock(account, password)
   213  		if err == nil {
   214  			log.Info("Unlocked account", "address", account.Address.Hex())
   215  			return account, password
   216  		}
   217  		if err, ok := err.(*keystore.AmbiguousAddrError); ok {
   218  			log.Info("Unlocked account", "address", account.Address.Hex())
   219  			return ambiguousAddrRecovery(ks, err, password), password
   220  		}
   221  		if err != keystore.ErrDecrypt {
   222  //如果错误与解密无关,则无需再次提示。
   223  			break
   224  		}
   225  	}
   226  //所有的审判都是为了解锁账户,救市
   227  	utils.Fatalf("Failed to unlock account %s (%v)", address, err)
   228  
   229  	return accounts.Account{}, ""
   230  }
   231  
   232  //getpassphrase检索与帐户关联的密码,或者获取
   233  //从预加载的密码短语列表中,或从用户交互式请求。
   234  func getPassPhrase(prompt string, confirmation bool, i int, passwords []string) string {
   235  //如果提供了密码列表,请从中检索
   236  	if len(passwords) > 0 {
   237  		if i < len(passwords) {
   238  			return passwords[i]
   239  		}
   240  		return passwords[len(passwords)-1]
   241  	}
   242  //否则提示用户输入密码
   243  	if prompt != "" {
   244  		fmt.Println(prompt)
   245  	}
   246  	password, err := console.Stdin.PromptPassword("Passphrase: ")
   247  	if err != nil {
   248  		utils.Fatalf("Failed to read passphrase: %v", err)
   249  	}
   250  	if confirmation {
   251  		confirm, err := console.Stdin.PromptPassword("Repeat passphrase: ")
   252  		if err != nil {
   253  			utils.Fatalf("Failed to read passphrase confirmation: %v", err)
   254  		}
   255  		if password != confirm {
   256  			utils.Fatalf("Passphrases do not match")
   257  		}
   258  	}
   259  	return password
   260  }
   261  
   262  func ambiguousAddrRecovery(ks *keystore.KeyStore, err *keystore.AmbiguousAddrError, auth string) accounts.Account {
   263  	fmt.Printf("Multiple key files exist for address %x:\n", err.Addr)
   264  	for _, a := range err.Matches {
   265  		fmt.Println("  ", a.URL)
   266  	}
   267  	fmt.Println("Testing your passphrase against all of them...")
   268  	var match *accounts.Account
   269  	for _, a := range err.Matches {
   270  		if err := ks.Unlock(a, auth); err == nil {
   271  			match = &a
   272  			break
   273  		}
   274  	}
   275  	if match == nil {
   276  		utils.Fatalf("None of the listed files could be unlocked.")
   277  	}
   278  	fmt.Printf("Your passphrase unlocked %s\n", match.URL)
   279  	fmt.Println("In order to avoid this warning, you need to remove the following duplicate key files:")
   280  	for _, a := range err.Matches {
   281  		if a != *match {
   282  			fmt.Println("  ", a.URL)
   283  		}
   284  	}
   285  	return *match
   286  }
   287  
   288  //accountcreate在cli标志定义的keystore中创建一个新帐户。
   289  func accountCreate(ctx *cli.Context) error {
   290  	cfg := gethConfig{Node: defaultNodeConfig()}
   291  //加载配置文件。
   292  	if file := ctx.GlobalString(configFileFlag.Name); file != "" {
   293  		if err := loadConfig(file, &cfg); err != nil {
   294  			utils.Fatalf("%v", err)
   295  		}
   296  	}
   297  	utils.SetNodeConfig(ctx, &cfg.Node)
   298  	scryptN, scryptP, keydir, err := cfg.Node.AccountConfig()
   299  
   300  	if err != nil {
   301  		utils.Fatalf("Failed to read configuration: %v", err)
   302  	}
   303  
   304  	password := getPassPhrase("Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0, utils.MakePasswordList(ctx))
   305  
   306  	address, err := keystore.StoreKey(keydir, password, scryptN, scryptP)
   307  
   308  	if err != nil {
   309  		utils.Fatalf("Failed to create account: %v", err)
   310  	}
   311  	fmt.Printf("Address: {%x}\n", address)
   312  	return nil
   313  }
   314  
   315  //accountupdate将帐户从以前的格式转换为当前格式
   316  //第一,也提供了改变通行短语的可能性。
   317  func accountUpdate(ctx *cli.Context) error {
   318  	if len(ctx.Args()) == 0 {
   319  		utils.Fatalf("No accounts specified to update")
   320  	}
   321  	stack, _ := makeConfigNode(ctx)
   322  	ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   323  
   324  	for _, addr := range ctx.Args() {
   325  		account, oldPassword := unlockAccount(ctx, ks, addr, 0, nil)
   326  		newPassword := getPassPhrase("Please give a new password. Do not forget this password.", true, 0, nil)
   327  		if err := ks.Update(account, oldPassword, newPassword); err != nil {
   328  			utils.Fatalf("Could not update the account: %v", err)
   329  		}
   330  	}
   331  	return nil
   332  }
   333  
   334  func importWallet(ctx *cli.Context) error {
   335  	keyfile := ctx.Args().First()
   336  	if len(keyfile) == 0 {
   337  		utils.Fatalf("keyfile must be given as argument")
   338  	}
   339  	keyJSON, err := ioutil.ReadFile(keyfile)
   340  	if err != nil {
   341  		utils.Fatalf("Could not read wallet file: %v", err)
   342  	}
   343  
   344  	stack, _ := makeConfigNode(ctx)
   345  	passphrase := getPassPhrase("", false, 0, utils.MakePasswordList(ctx))
   346  
   347  	ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   348  	acct, err := ks.ImportPreSaleKey(keyJSON, passphrase)
   349  	if err != nil {
   350  		utils.Fatalf("%v", err)
   351  	}
   352  	fmt.Printf("Address: {%x}\n", acct.Address)
   353  	return nil
   354  }
   355  
   356  func accountImport(ctx *cli.Context) error {
   357  	keyfile := ctx.Args().First()
   358  	if len(keyfile) == 0 {
   359  		utils.Fatalf("keyfile must be given as argument")
   360  	}
   361  	key, err := crypto.LoadECDSA(keyfile)
   362  	if err != nil {
   363  		utils.Fatalf("Failed to load the private key: %v", err)
   364  	}
   365  	stack, _ := makeConfigNode(ctx)
   366  	passphrase := getPassPhrase("Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0, utils.MakePasswordList(ctx))
   367  
   368  	ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   369  	acct, err := ks.ImportECDSA(key, passphrase)
   370  	if err != nil {
   371  		utils.Fatalf("Could not create the account: %v", err)
   372  	}
   373  	fmt.Printf("Address: {%x}\n", acct.Address)
   374  	return nil
   375  }
   376