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