github.com/palisadeinc/bor@v0.0.0-20230615125219-ab7196213d15/internal/cli/account_import.go (about)

     1  package cli
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/ethereum/go-ethereum/cmd/utils"
     8  	"github.com/ethereum/go-ethereum/crypto"
     9  	"github.com/ethereum/go-ethereum/internal/cli/flagset"
    10  )
    11  
    12  type AccountImportCommand struct {
    13  	*Meta
    14  }
    15  
    16  // MarkDown implements cli.MarkDown interface
    17  func (a *AccountImportCommand) MarkDown() string {
    18  	items := []string{
    19  		"# Account import",
    20  		"The ```account import``` command imports an account in Json format to the Bor data directory.",
    21  		a.Flags().MarkDown(),
    22  	}
    23  
    24  	return strings.Join(items, "\n\n")
    25  }
    26  
    27  // Help implements the cli.Command interface
    28  func (a *AccountImportCommand) Help() string {
    29  	return `Usage: bor account import
    30  
    31    Import a private key into a new account.
    32  
    33    Import an account:
    34  
    35      $ bor account import key.json
    36  
    37    ` + a.Flags().Help()
    38  }
    39  
    40  func (a *AccountImportCommand) Flags() *flagset.Flagset {
    41  	return a.NewFlagSet("account import")
    42  }
    43  
    44  // Synopsis implements the cli.Command interface
    45  func (a *AccountImportCommand) Synopsis() string {
    46  	return "Import a private key into a new account"
    47  }
    48  
    49  // Run implements the cli.Command interface
    50  func (a *AccountImportCommand) Run(args []string) int {
    51  	flags := a.Flags()
    52  	if err := flags.Parse(args); err != nil {
    53  		a.UI.Error(err.Error())
    54  		return 1
    55  	}
    56  
    57  	args = flags.Args()
    58  	if len(args) != 1 {
    59  		a.UI.Error("Expected one argument")
    60  		return 1
    61  	}
    62  
    63  	key, err := crypto.LoadECDSA(args[0])
    64  
    65  	if err != nil {
    66  		a.UI.Error(fmt.Sprintf("Failed to load the private key '%s': %v", args[0], err))
    67  		return 1
    68  	}
    69  
    70  	keystore, err := a.GetKeystore()
    71  	if err != nil {
    72  		a.UI.Error(fmt.Sprintf("Failed to get keystore: %v", err))
    73  		return 1
    74  	}
    75  
    76  	password, err := a.AskPassword()
    77  	if err != nil {
    78  		a.UI.Error(err.Error())
    79  		return 1
    80  	}
    81  
    82  	acct, err := keystore.ImportECDSA(key, password)
    83  	if err != nil {
    84  		utils.Fatalf("Could not create the account: %v", err)
    85  	}
    86  
    87  	a.UI.Output(fmt.Sprintf("Account created: %s", acct.Address.String()))
    88  
    89  	return 0
    90  }