github.com/pslzym/go-ethereum@v1.8.17-0.20180926104442-4b6824e07b1b/signer/core/cliui.go (about)

     1  // Copyright 2018 The go-ethereum Authors
     2  // This file is part of go-ethereum.
     3  //
     4  // go-ethereum is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // go-ethereum is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU General Public License
    15  // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package core
    18  
    19  import (
    20  	"bufio"
    21  	"fmt"
    22  	"os"
    23  	"strings"
    24  
    25  	"sync"
    26  
    27  	"github.com/davecgh/go-spew/spew"
    28  	"github.com/ethereum/go-ethereum/common/hexutil"
    29  	"github.com/ethereum/go-ethereum/internal/ethapi"
    30  	"github.com/ethereum/go-ethereum/log"
    31  	"golang.org/x/crypto/ssh/terminal"
    32  )
    33  
    34  type CommandlineUI struct {
    35  	in *bufio.Reader
    36  	mu sync.Mutex
    37  }
    38  
    39  func NewCommandlineUI() *CommandlineUI {
    40  	return &CommandlineUI{in: bufio.NewReader(os.Stdin)}
    41  }
    42  
    43  // readString reads a single line from stdin, trimming if from spaces, enforcing
    44  // non-emptyness.
    45  func (ui *CommandlineUI) readString() string {
    46  	for {
    47  		fmt.Printf("> ")
    48  		text, err := ui.in.ReadString('\n')
    49  		if err != nil {
    50  			log.Crit("Failed to read user input", "err", err)
    51  		}
    52  		if text = strings.TrimSpace(text); text != "" {
    53  			return text
    54  		}
    55  	}
    56  }
    57  
    58  // readPassword reads a single line from stdin, trimming it from the trailing new
    59  // line and returns it. The input will not be echoed.
    60  func (ui *CommandlineUI) readPassword() string {
    61  	fmt.Printf("Enter password to approve:\n")
    62  	fmt.Printf("> ")
    63  
    64  	text, err := terminal.ReadPassword(int(os.Stdin.Fd()))
    65  	if err != nil {
    66  		log.Crit("Failed to read password", "err", err)
    67  	}
    68  	fmt.Println()
    69  	fmt.Println("-----------------------")
    70  	return string(text)
    71  }
    72  
    73  // readPassword reads a single line from stdin, trimming it from the trailing new
    74  // line and returns it. The input will not be echoed.
    75  func (ui *CommandlineUI) readPasswordText(inputstring string) string {
    76  	fmt.Printf("Enter %s:\n", inputstring)
    77  	fmt.Printf("> ")
    78  	text, err := terminal.ReadPassword(int(os.Stdin.Fd()))
    79  	if err != nil {
    80  		log.Crit("Failed to read password", "err", err)
    81  	}
    82  	fmt.Println("-----------------------")
    83  	return string(text)
    84  }
    85  
    86  // confirm returns true if user enters 'Yes', otherwise false
    87  func (ui *CommandlineUI) confirm() bool {
    88  	fmt.Printf("Approve? [y/N]:\n")
    89  	if ui.readString() == "y" {
    90  		return true
    91  	}
    92  	fmt.Println("-----------------------")
    93  	return false
    94  }
    95  
    96  func showMetadata(metadata Metadata) {
    97  	fmt.Printf("Request context:\n\t%v -> %v -> %v\n", metadata.Remote, metadata.Scheme, metadata.Local)
    98  	fmt.Printf("\nAdditional HTTP header data, provided by the external caller:\n")
    99  	fmt.Printf("\tUser-Agent: %v\n\tOrigin: %v\n", metadata.UserAgent, metadata.Origin)
   100  }
   101  
   102  // ApproveTx prompt the user for confirmation to request to sign Transaction
   103  func (ui *CommandlineUI) ApproveTx(request *SignTxRequest) (SignTxResponse, error) {
   104  	ui.mu.Lock()
   105  	defer ui.mu.Unlock()
   106  	weival := request.Transaction.Value.ToInt()
   107  	fmt.Printf("--------- Transaction request-------------\n")
   108  	if to := request.Transaction.To; to != nil {
   109  		fmt.Printf("to:    %v\n", to.Original())
   110  		if !to.ValidChecksum() {
   111  			fmt.Printf("\nWARNING: Invalid checksum on to-address!\n\n")
   112  		}
   113  	} else {
   114  		fmt.Printf("to:    <contact creation>\n")
   115  	}
   116  	fmt.Printf("from:     %v\n", request.Transaction.From.String())
   117  	fmt.Printf("value:    %v wei\n", weival)
   118  	fmt.Printf("gas:      %v (%v)\n", request.Transaction.Gas, uint64(request.Transaction.Gas))
   119  	fmt.Printf("gasprice: %v wei\n", request.Transaction.GasPrice.ToInt())
   120  	fmt.Printf("nonce:    %v (%v)\n", request.Transaction.Nonce, uint64(request.Transaction.Nonce))
   121  	if request.Transaction.Data != nil {
   122  		d := *request.Transaction.Data
   123  		if len(d) > 0 {
   124  
   125  			fmt.Printf("data:     %v\n", hexutil.Encode(d))
   126  		}
   127  	}
   128  	if request.Callinfo != nil {
   129  		fmt.Printf("\nTransaction validation:\n")
   130  		for _, m := range request.Callinfo {
   131  			fmt.Printf("  * %s : %s\n", m.Typ, m.Message)
   132  		}
   133  		fmt.Println()
   134  
   135  	}
   136  	fmt.Printf("\n")
   137  	showMetadata(request.Meta)
   138  	fmt.Printf("-------------------------------------------\n")
   139  	if !ui.confirm() {
   140  		return SignTxResponse{request.Transaction, false, ""}, nil
   141  	}
   142  	return SignTxResponse{request.Transaction, true, ui.readPassword()}, nil
   143  }
   144  
   145  // ApproveSignData prompt the user for confirmation to request to sign data
   146  func (ui *CommandlineUI) ApproveSignData(request *SignDataRequest) (SignDataResponse, error) {
   147  	ui.mu.Lock()
   148  	defer ui.mu.Unlock()
   149  
   150  	fmt.Printf("-------- Sign data request--------------\n")
   151  	fmt.Printf("Account:  %s\n", request.Address.String())
   152  	fmt.Printf("message:  \n%q\n", request.Message)
   153  	fmt.Printf("raw data: \n%v\n", request.Rawdata)
   154  	fmt.Printf("message hash:  %v\n", request.Hash)
   155  	fmt.Printf("-------------------------------------------\n")
   156  	showMetadata(request.Meta)
   157  	if !ui.confirm() {
   158  		return SignDataResponse{false, ""}, nil
   159  	}
   160  	return SignDataResponse{true, ui.readPassword()}, nil
   161  }
   162  
   163  // ApproveExport prompt the user for confirmation to export encrypted Account json
   164  func (ui *CommandlineUI) ApproveExport(request *ExportRequest) (ExportResponse, error) {
   165  	ui.mu.Lock()
   166  	defer ui.mu.Unlock()
   167  
   168  	fmt.Printf("-------- Export Account request--------------\n")
   169  	fmt.Printf("A request has been made to export the (encrypted) keyfile\n")
   170  	fmt.Printf("Approving this operation means that the caller obtains the (encrypted) contents\n")
   171  	fmt.Printf("\n")
   172  	fmt.Printf("Account:  %x\n", request.Address)
   173  	//fmt.Printf("keyfile:  \n%v\n", request.file)
   174  	fmt.Printf("-------------------------------------------\n")
   175  	showMetadata(request.Meta)
   176  	return ExportResponse{ui.confirm()}, nil
   177  }
   178  
   179  // ApproveImport prompt the user for confirmation to import Account json
   180  func (ui *CommandlineUI) ApproveImport(request *ImportRequest) (ImportResponse, error) {
   181  	ui.mu.Lock()
   182  	defer ui.mu.Unlock()
   183  
   184  	fmt.Printf("-------- Import Account request--------------\n")
   185  	fmt.Printf("A request has been made to import an encrypted keyfile\n")
   186  	fmt.Printf("-------------------------------------------\n")
   187  	showMetadata(request.Meta)
   188  	if !ui.confirm() {
   189  		return ImportResponse{false, "", ""}, nil
   190  	}
   191  	return ImportResponse{true, ui.readPasswordText("Old password"), ui.readPasswordText("New password")}, nil
   192  }
   193  
   194  // ApproveListing prompt the user for confirmation to list accounts
   195  // the list of accounts to list can be modified by the UI
   196  func (ui *CommandlineUI) ApproveListing(request *ListRequest) (ListResponse, error) {
   197  
   198  	ui.mu.Lock()
   199  	defer ui.mu.Unlock()
   200  
   201  	fmt.Printf("-------- List Account request--------------\n")
   202  	fmt.Printf("A request has been made to list all accounts. \n")
   203  	fmt.Printf("You can select which accounts the caller can see\n")
   204  	for _, account := range request.Accounts {
   205  		fmt.Printf("  [x] %v\n", account.Address.Hex())
   206  		fmt.Printf("    URL: %v\n", account.URL)
   207  		fmt.Printf("    Type: %v\n", account.Typ)
   208  	}
   209  	fmt.Printf("-------------------------------------------\n")
   210  	showMetadata(request.Meta)
   211  	if !ui.confirm() {
   212  		return ListResponse{nil}, nil
   213  	}
   214  	return ListResponse{request.Accounts}, nil
   215  }
   216  
   217  // ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller
   218  func (ui *CommandlineUI) ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) {
   219  
   220  	ui.mu.Lock()
   221  	defer ui.mu.Unlock()
   222  
   223  	fmt.Printf("-------- New Account request--------------\n\n")
   224  	fmt.Printf("A request has been made to create a new account. \n")
   225  	fmt.Printf("Approving this operation means that a new account is created,\n")
   226  	fmt.Printf("and the address is returned to the external caller\n\n")
   227  	showMetadata(request.Meta)
   228  	if !ui.confirm() {
   229  		return NewAccountResponse{false, ""}, nil
   230  	}
   231  	return NewAccountResponse{true, ui.readPassword()}, nil
   232  }
   233  
   234  // ShowError displays error message to user
   235  func (ui *CommandlineUI) ShowError(message string) {
   236  	fmt.Printf("-------- Error message from Clef-----------\n")
   237  	fmt.Println(message)
   238  	fmt.Printf("-------------------------------------------\n")
   239  }
   240  
   241  // ShowInfo displays info message to user
   242  func (ui *CommandlineUI) ShowInfo(message string) {
   243  	fmt.Printf("Info: %v\n", message)
   244  }
   245  
   246  func (ui *CommandlineUI) OnApprovedTx(tx ethapi.SignTransactionResult) {
   247  	fmt.Printf("Transaction signed:\n ")
   248  	spew.Dump(tx.Tx)
   249  }
   250  
   251  func (ui *CommandlineUI) OnSignerStartup(info StartupInfo) {
   252  
   253  	fmt.Printf("------- Signer info -------\n")
   254  	for k, v := range info.Info {
   255  		fmt.Printf("* %v : %v\n", k, v)
   256  	}
   257  }