github.com/iotexproject/iotex-core@v1.14.1-rc1/ioctl/cmd/did/didgenerate.go (about)

     1  // Copyright (c) 2020 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 did
     7  
     8  import (
     9  	"crypto/ecdsa"
    10  	"encoding/hex"
    11  
    12  	"github.com/spf13/cobra"
    13  
    14  	"github.com/iotexproject/iotex-core/ioctl/cmd/action"
    15  	"github.com/iotexproject/iotex-core/ioctl/config"
    16  	"github.com/iotexproject/iotex-core/ioctl/output"
    17  )
    18  
    19  // Multi-language support
    20  var (
    21  	_generateCmdShorts = map[config.Language]string{
    22  		config.English: "Generate DID document using private key from wallet",
    23  		config.Chinese: "用钱包中的私钥产生DID document",
    24  	}
    25  	_generateCmdUses = map[config.Language]string{
    26  		config.English: "generate [-s SIGNER]",
    27  		config.Chinese: "generate [-s 签署人]",
    28  	}
    29  )
    30  
    31  // _didGenerateCmd represents the generate command
    32  var _didGenerateCmd = &cobra.Command{
    33  	Use:   config.TranslateInLang(_generateCmdUses, config.UILanguage),
    34  	Short: config.TranslateInLang(_generateCmdShorts, config.UILanguage),
    35  	Args:  cobra.ExactArgs(0),
    36  	RunE: func(cmd *cobra.Command, args []string) error {
    37  		cmd.SilenceUsage = true
    38  		err := generate()
    39  		return output.PrintError(err)
    40  	},
    41  }
    42  
    43  func init() {
    44  	action.RegisterWriteCommand(_didGenerateCmd)
    45  }
    46  
    47  func generate() error {
    48  	key, _, err := loadPrivateKey()
    49  	if err != nil {
    50  		return err
    51  	}
    52  	generatedMessage, err := generateFromSigner(key)
    53  	if err != nil {
    54  		return err
    55  	}
    56  	output.PrintResult(generatedMessage)
    57  	return nil
    58  }
    59  
    60  func generateFromSigner(key *ecdsa.PrivateKey) (generatedMessage string, err error) {
    61  	publicKey, err := loadPublicKey(key)
    62  	if err != nil {
    63  		return "", err
    64  	}
    65  	doc, err := NewDIDDoc(publicKey)
    66  	if err != nil {
    67  		return "", output.NewError(output.ConvertError, "", err)
    68  	}
    69  	msg, err := doc.JSON()
    70  	if err != nil {
    71  		return "", output.NewError(output.ConvertError, "", err)
    72  	}
    73  	hash, err := doc.Hash()
    74  	if err != nil {
    75  		return "", output.NewError(output.ConvertError, "", err)
    76  	}
    77  
    78  	generatedMessage = msg + "\n\nThe hex encoded SHA256 hash of the DID doc is:" + hex.EncodeToString(hash[:])
    79  	return
    80  }