github.com/iotexproject/iotex-core@v1.14.1-rc1/ioctl/cmd/account/accountsign.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  	"github.com/spf13/cobra"
    10  
    11  	"github.com/iotexproject/iotex-core/ioctl/config"
    12  	"github.com/iotexproject/iotex-core/ioctl/output"
    13  	"github.com/iotexproject/iotex-core/ioctl/util"
    14  )
    15  
    16  var signer string
    17  
    18  // Multi-language support
    19  var (
    20  	_signCmdShorts = map[config.Language]string{
    21  		config.English: "Sign message with private key from wallet",
    22  		config.Chinese: "用钱包中的私钥对信息签名",
    23  	}
    24  	_signCmdUses = map[config.Language]string{
    25  		config.English: "sign MESSAGE [-s SIGNER]",
    26  		config.Chinese: "sign 信息 [-s 签署人]",
    27  	}
    28  	_flagSignerUsages = map[config.Language]string{
    29  		config.English: "choose a signing account",
    30  		config.Chinese: "选择一个签名账户",
    31  	}
    32  )
    33  
    34  // _accountSignCmd represents the account sign command
    35  var _accountSignCmd = &cobra.Command{
    36  	Use:   config.TranslateInLang(_signCmdUses, config.UILanguage),
    37  	Short: config.TranslateInLang(_signCmdShorts, config.UILanguage),
    38  	Args:  cobra.ExactArgs(1),
    39  	RunE: func(cmd *cobra.Command, args []string) error {
    40  		cmd.SilenceUsage = true
    41  		err := accountSign(args[0])
    42  		return output.PrintError(err)
    43  	},
    44  }
    45  
    46  func init() {
    47  	_accountSignCmd.Flags().StringVarP(&signer, "signer", "s", "", config.TranslateInLang(_flagSignerUsages, config.UILanguage))
    48  }
    49  
    50  func accountSign(msg string) error {
    51  	var (
    52  		addr string
    53  		err  error
    54  	)
    55  	if util.AliasIsHdwalletKey(signer) {
    56  		addr = signer
    57  	} else {
    58  		addr, err = util.Address(signer)
    59  		if err != nil {
    60  			return output.NewError(output.AddressError, "failed to get address", err)
    61  		}
    62  	}
    63  	signedMessage, err := Sign(addr, "", msg)
    64  	if err != nil {
    65  		return output.NewError(output.KeystoreError, "failed to sign message", err)
    66  	}
    67  	output.PrintResult(signedMessage)
    68  	return nil
    69  }