github.com/iotexproject/iotex-core@v1.14.1-rc1/ioctl/newcmd/account/accountcreate.go (about)

     1  // Copyright (c) 2019 IoTeX Foundation
     2  // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
     3  // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
     4  // This source code is governed by Apache License 2.0 that can be found in the LICENSE file.
     5  
     6  package account
     7  
     8  import (
     9  	"encoding/json"
    10  	"fmt"
    11  	"log"
    12  
    13  	"github.com/iotexproject/go-pkgs/crypto"
    14  	"github.com/pkg/errors"
    15  	"github.com/spf13/cobra"
    16  
    17  	"github.com/iotexproject/iotex-core/ioctl"
    18  	"github.com/iotexproject/iotex-core/ioctl/config"
    19  )
    20  
    21  // Multi-language support
    22  var (
    23  	_createShorts = map[config.Language]string{
    24  		config.English: "Create N new accounts and print them",
    25  		config.Chinese: "创建 N 个新账户,并打印",
    26  	}
    27  	_createFlagUsages = map[config.Language]string{
    28  		config.English: "number of accounts to create",
    29  		config.Chinese: "指定创建账户的数量",
    30  	}
    31  	_failToGenerateNewPrivateKey = map[config.Language]string{
    32  		config.English: "failed to generate new private key",
    33  		config.Chinese: "生成新私钥失败",
    34  	}
    35  	_failToGenerateNewPrivateKeySm2 = map[config.Language]string{
    36  		config.English: "failed to generate new sm2 private key",
    37  		config.Chinese: "生成新sm2私钥失败",
    38  	}
    39  	_failToConvertPublicKeyIntoAddress = map[config.Language]string{
    40  		config.English: "failed to convert public key into address",
    41  		config.Chinese: "将公钥转换为地址失败",
    42  	}
    43  )
    44  
    45  // NewAccountCreate represents the account create command
    46  func NewAccountCreate(client ioctl.Client) *cobra.Command {
    47  	var numAccounts uint
    48  	short, _ := client.SelectTranslation(_createShorts)
    49  	usage, _ := client.SelectTranslation(_createFlagUsages)
    50  	_failToGenerateNewPrivateKey, _ := client.SelectTranslation(_failToGenerateNewPrivateKey)
    51  	_failToGenerateNewPrivateKeySm2, _ := client.SelectTranslation(_failToGenerateNewPrivateKeySm2)
    52  	_failToConvertPublicKeyIntoAddress, _ := client.SelectTranslation(_failToConvertPublicKeyIntoAddress)
    53  
    54  	cmd := &cobra.Command{
    55  		Use:   "create",
    56  		Short: short,
    57  		Args:  cobra.ExactArgs(0),
    58  		RunE: func(cmd *cobra.Command, args []string) error {
    59  			cmd.SilenceUsage = true
    60  			var err error
    61  			var private crypto.PrivateKey
    62  
    63  			newAccounts := make([]generatedAccount, 0)
    64  			for i := 0; i < int(numAccounts); i++ {
    65  				if !client.IsCryptoSm2() {
    66  					private, err = crypto.GenerateKey()
    67  					if err != nil {
    68  						return errors.Wrap(err, _failToGenerateNewPrivateKey)
    69  					}
    70  				} else {
    71  					private, err = crypto.GenerateKeySm2()
    72  					if err != nil {
    73  						return errors.Wrap(err, _failToGenerateNewPrivateKeySm2)
    74  					}
    75  				}
    76  
    77  				addr := private.PublicKey().Address()
    78  				if addr == nil {
    79  					return errors.New(_failToConvertPublicKeyIntoAddress)
    80  				}
    81  				newAccount := generatedAccount{
    82  					Address:    addr.String(),
    83  					PrivateKey: fmt.Sprintf("%x", private.Bytes()),
    84  					PublicKey:  fmt.Sprintf("%x", private.PublicKey().Bytes()),
    85  				}
    86  				newAccounts = append(newAccounts, newAccount)
    87  			}
    88  
    89  			message := createMessage{Accounts: newAccounts}
    90  			cmd.Println(message.String())
    91  			return nil
    92  		},
    93  	}
    94  	cmd.Flags().UintVarP(&numAccounts, "num", "n", 1, usage)
    95  	return cmd
    96  }
    97  
    98  type createMessage struct {
    99  	Accounts []generatedAccount `json:"accounts"`
   100  }
   101  
   102  type generatedAccount struct {
   103  	Address    string `json:"address"`
   104  	PrivateKey string `json:"privateKey"`
   105  	PublicKey  string `json:"publicKey"`
   106  }
   107  
   108  func (m *createMessage) String() string {
   109  	byteAsJSON, err := json.MarshalIndent(m, "", "  ")
   110  	if err != nil {
   111  		log.Panic(err)
   112  	}
   113  	return fmt.Sprint(string(byteAsJSON))
   114  }