github.com/iotexproject/iotex-core@v1.14.1-rc1/ioctl/cmd/account/accountlist.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 "fmt" 10 "strings" 11 12 "github.com/ethereum/go-ethereum/accounts/keystore" 13 "github.com/spf13/cobra" 14 15 "github.com/iotexproject/iotex-address/address" 16 17 "github.com/iotexproject/iotex-core/ioctl/cmd/alias" 18 "github.com/iotexproject/iotex-core/ioctl/config" 19 "github.com/iotexproject/iotex-core/ioctl/output" 20 ) 21 22 // Multi-language support 23 var ( 24 _listCmdShorts = map[config.Language]string{ 25 config.English: "List existing account for ioctl", 26 config.Chinese: "列出ioctl中已存在的账户", 27 } 28 ) 29 30 // _accountListCmd represents the account list command 31 var _accountListCmd = &cobra.Command{ 32 Use: "list", 33 Short: config.TranslateInLang(_listCmdShorts, config.UILanguage), 34 Args: cobra.ExactArgs(0), 35 RunE: func(cmd *cobra.Command, args []string) error { 36 cmd.SilenceUsage = true 37 err := accountList() 38 return output.PrintError(err) 39 }, 40 } 41 42 type listMessage struct { 43 Accounts []account `json:"accounts"` 44 } 45 46 type account struct { 47 Address string `json:"address"` 48 Alias string `json:"alias"` 49 } 50 51 func accountList() error { 52 message := listMessage{} 53 aliases := alias.GetAliasMap() 54 55 if CryptoSm2 { 56 sm2Accounts, err := listSm2Account() 57 if err != nil { 58 return output.NewError(output.ReadFileError, "failed to get sm2 accounts", err) 59 } 60 for _, addr := range sm2Accounts { 61 message.Accounts = append(message.Accounts, account{ 62 Address: addr, 63 Alias: aliases[addr], 64 }) 65 } 66 } else { 67 ks := keystore.NewKeyStore(config.ReadConfig.Wallet, 68 keystore.StandardScryptN, keystore.StandardScryptP) 69 for _, v := range ks.Accounts() { 70 addr, err := address.FromBytes(v.Address.Bytes()) 71 if err != nil { 72 return output.NewError(output.ConvertError, "failed to convert bytes into address", err) 73 } 74 message.Accounts = append(message.Accounts, account{ 75 Address: addr.String(), 76 Alias: aliases[addr.String()], 77 }) 78 } 79 } 80 81 fmt.Println(message.String()) 82 return nil 83 } 84 85 func (m *listMessage) String() string { 86 if output.Format == "" { 87 lines := make([]string, 0) 88 for _, account := range m.Accounts { 89 line := account.Address 90 if account.Alias != "" { 91 line += " - " + account.Alias 92 } 93 lines = append(lines, line) 94 } 95 96 return strings.Join(lines, "\n") 97 } 98 return output.FormatString(output.Result, m) 99 }