github.com/iotexproject/iotex-core@v1.14.1-rc1/tools/addrgen/internal/cmd/generate.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 cmd 7 8 import ( 9 "fmt" 10 "strings" 11 12 "github.com/iotexproject/go-pkgs/crypto" 13 "github.com/spf13/cobra" 14 "go.uber.org/zap" 15 16 "github.com/iotexproject/iotex-core/pkg/log" 17 ) 18 19 // generateCmd represents the generate command 20 var generateCmd = &cobra.Command{ 21 Use: "generate [# number]", 22 Short: "Generates n number of address key pairs.", 23 Long: `Generates n number of address key pairs.`, 24 Run: func(cmd *cobra.Command, args []string) { 25 fmt.Println(generate(args)) 26 }, 27 } 28 29 var _addrNum int 30 31 func generate(_ []string) string { 32 items := make([]string, _addrNum) 33 for i := 0; i < _addrNum; i++ { 34 private, err := crypto.GenerateKey() 35 if err != nil { 36 log.L().Fatal("failed to create key pair", zap.Error(err)) 37 } 38 priKeyBytes := private.Bytes() 39 pubKeyBytes := private.PublicKey().Bytes() 40 items[i] = fmt.Sprintf( 41 "{\"PublicKey\": \"%x\", \"PrivateKey\": \"%x\"}", 42 pubKeyBytes, 43 priKeyBytes, 44 ) 45 } 46 return "[" + strings.Join(items, ",") + "]" 47 } 48 49 func init() { 50 generateCmd.Flags().IntVarP(&_addrNum, "number", "n", 10, "number of addresses to be generated") 51 rootCmd.AddCommand(generateCmd) 52 }