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