github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/cmd/qctkey/utils.go (about)

     1  
     2  package main
     3  
     4  import (
     5  	"encoding/json"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"strings"
     9  
    10  	"github.com/quickchainproject/quickchain/cmd/utils"
    11  	"github.com/quickchainproject/quickchain/console"
    12  	"github.com/quickchainproject/quickchain/crypto"
    13  	"gopkg.in/urfave/cli.v1"
    14  )
    15  
    16  // getPassPhrase obtains a passphrase given by the user.  It first checks the
    17  // --passphrase command line flag and ultimately prompts the user for a
    18  // passphrase.
    19  func getPassPhrase(ctx *cli.Context, confirmation bool) string {
    20  	// Look for the --passphrase flag.
    21  	passphraseFile := ctx.String(passphraseFlag.Name)
    22  	if passphraseFile != "" {
    23  		content, err := ioutil.ReadFile(passphraseFile)
    24  		if err != nil {
    25  			utils.Fatalf("Failed to read passphrase file '%s': %v",
    26  				passphraseFile, err)
    27  		}
    28  		return strings.TrimRight(string(content), "\r\n")
    29  	}
    30  
    31  	// Otherwise prompt the user for the passphrase.
    32  	passphrase, err := console.Stdin.PromptPassword("Passphrase: ")
    33  	if err != nil {
    34  		utils.Fatalf("Failed to read passphrase: %v", err)
    35  	}
    36  	if confirmation {
    37  		confirm, err := console.Stdin.PromptPassword("Repeat passphrase: ")
    38  		if err != nil {
    39  			utils.Fatalf("Failed to read passphrase confirmation: %v", err)
    40  		}
    41  		if passphrase != confirm {
    42  			utils.Fatalf("Passphrases do not match")
    43  		}
    44  	}
    45  	return passphrase
    46  }
    47  
    48  // signHash is a helper function that calculates a hash for the given message
    49  // that can be safely used to calculate a signature from.
    50  //
    51  // The hash is calulcated as
    52  //   keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
    53  //
    54  // This gives context to the signed message and prevents signing of transactions.
    55  func signHash(data []byte) []byte {
    56  	msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
    57  	return crypto.Keccak256([]byte(msg))
    58  }
    59  
    60  // mustPrintJSON prints the JSON encoding of the given object and
    61  // exits the program with an error message when the marshaling fails.
    62  func mustPrintJSON(jsonObject interface{}) {
    63  	str, err := json.MarshalIndent(jsonObject, "", "  ")
    64  	if err != nil {
    65  		utils.Fatalf("Failed to marshal JSON object: %v", err)
    66  	}
    67  	fmt.Println(string(str))
    68  }