github.com/verovm/record-replay@v1.9.7/signer/core/cliui.go (about)

     1  // Copyright 2018 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser 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  // The go-ethereum library 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 Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. 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  
    91  	fmt.Printf("## %s\n\n%s\n", info.Title, info.Prompt)
    92  	if info.IsPassword {
    93  		fmt.Printf("> ")
    94  		text, err := terminal.ReadPassword(int(os.Stdin.Fd()))
    95  		if err != nil {
    96  			log.Error("Failed to read password", "err", err)
    97  		}
    98  		fmt.Println("-----------------------")
    99  		return UserInputResponse{string(text)}, err
   100  	}
   101  	text := ui.readString()
   102  	fmt.Println("-----------------------")
   103  	return UserInputResponse{text}, nil
   104  }
   105  
   106  // confirm returns true if user enters 'Yes', otherwise false
   107  func (ui *CommandlineUI) confirm() bool {
   108  	fmt.Printf("Approve? [y/N]:\n")
   109  	if ui.readString() == "y" {
   110  		return true
   111  	}
   112  	fmt.Println("-----------------------")
   113  	return false
   114  }
   115  
   116  func showMetadata(metadata Metadata) {
   117  	fmt.Printf("Request context:\n\t%v -> %v -> %v\n", metadata.Remote, metadata.Scheme, metadata.Local)
   118  	fmt.Printf("\nAdditional HTTP header data, provided by the external caller:\n")
   119  	fmt.Printf("\tUser-Agent: %v\n\tOrigin: %v\n", metadata.UserAgent, metadata.Origin)
   120  }
   121  
   122  // ApproveTx prompt the user for confirmation to request to sign Transaction
   123  func (ui *CommandlineUI) ApproveTx(request *SignTxRequest) (SignTxResponse, error) {
   124  	ui.mu.Lock()
   125  	defer ui.mu.Unlock()
   126  	weival := request.Transaction.Value.ToInt()
   127  	fmt.Printf("--------- Transaction request-------------\n")
   128  	if to := request.Transaction.To; to != nil {
   129  		fmt.Printf("to:    %v\n", to.Original())
   130  		if !to.ValidChecksum() {
   131  			fmt.Printf("\nWARNING: Invalid checksum on to-address!\n\n")
   132  		}
   133  	} else {
   134  		fmt.Printf("to:    <contact creation>\n")
   135  	}
   136  	fmt.Printf("from:     %v\n", request.Transaction.From.String())
   137  	fmt.Printf("value:    %v wei\n", weival)
   138  	fmt.Printf("gas:      %v (%v)\n", request.Transaction.Gas, uint64(request.Transaction.Gas))
   139  	fmt.Printf("gasprice: %v wei\n", request.Transaction.GasPrice.ToInt())
   140  	fmt.Printf("nonce:    %v (%v)\n", request.Transaction.Nonce, uint64(request.Transaction.Nonce))
   141  	if request.Transaction.Data != nil {
   142  		d := *request.Transaction.Data
   143  		if len(d) > 0 {
   144  
   145  			fmt.Printf("data:     %v\n", hexutil.Encode(d))
   146  		}
   147  	}
   148  	if request.Callinfo != nil {
   149  		fmt.Printf("\nTransaction validation:\n")
   150  		for _, m := range request.Callinfo {
   151  			fmt.Printf("  * %s : %s\n", m.Typ, m.Message)
   152  		}
   153  		fmt.Println()
   154  
   155  	}
   156  	fmt.Printf("\n")
   157  	showMetadata(request.Meta)
   158  	fmt.Printf("-------------------------------------------\n")
   159  	if !ui.confirm() {
   160  		return SignTxResponse{request.Transaction, false}, nil
   161  	}
   162  	return SignTxResponse{request.Transaction, true}, nil
   163  }
   164  
   165  // ApproveSignData prompt the user for confirmation to request to sign data
   166  func (ui *CommandlineUI) ApproveSignData(request *SignDataRequest) (SignDataResponse, error) {
   167  	ui.mu.Lock()
   168  	defer ui.mu.Unlock()
   169  
   170  	fmt.Printf("-------- Sign data request--------------\n")
   171  	fmt.Printf("Account:  %s\n", request.Address.String())
   172  	fmt.Printf("messages:\n")
   173  	for _, nvt := range request.Messages {
   174  		fmt.Printf("\u00a0\u00a0%v\n", strings.TrimSpace(nvt.Pprint(1)))
   175  	}
   176  	fmt.Printf("raw data:  \n%q\n", request.Rawdata)
   177  	fmt.Printf("data 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}, nil
   184  }
   185  
   186  // ApproveListing prompt the user for confirmation to list accounts
   187  // the list of accounts to list can be modified by the UI
   188  func (ui *CommandlineUI) ApproveListing(request *ListRequest) (ListResponse, error) {
   189  	ui.mu.Lock()
   190  	defer ui.mu.Unlock()
   191  
   192  	fmt.Printf("-------- List Account request--------------\n")
   193  	fmt.Printf("A request has been made to list all accounts. \n")
   194  	fmt.Printf("You can select which accounts the caller can see\n")
   195  	for _, account := range request.Accounts {
   196  		fmt.Printf("  [x] %v\n", account.Address.Hex())
   197  		fmt.Printf("    URL: %v\n", account.URL)
   198  	}
   199  	fmt.Printf("-------------------------------------------\n")
   200  	showMetadata(request.Meta)
   201  	if !ui.confirm() {
   202  		return ListResponse{nil}, nil
   203  	}
   204  	return ListResponse{request.Accounts}, nil
   205  }
   206  
   207  // ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller
   208  func (ui *CommandlineUI) ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) {
   209  
   210  	ui.mu.Lock()
   211  	defer ui.mu.Unlock()
   212  
   213  	fmt.Printf("-------- New Account request--------------\n\n")
   214  	fmt.Printf("A request has been made to create a new account. \n")
   215  	fmt.Printf("Approving this operation means that a new account is created,\n")
   216  	fmt.Printf("and the address is returned to the external caller\n\n")
   217  	showMetadata(request.Meta)
   218  	if !ui.confirm() {
   219  		return NewAccountResponse{false}, nil
   220  	}
   221  	return NewAccountResponse{true}, nil
   222  }
   223  
   224  // ShowError displays error message to user
   225  func (ui *CommandlineUI) ShowError(message string) {
   226  	fmt.Printf("## Error \n%s\n", message)
   227  	fmt.Printf("-------------------------------------------\n")
   228  }
   229  
   230  // ShowInfo displays info message to user
   231  func (ui *CommandlineUI) ShowInfo(message string) {
   232  	fmt.Printf("## Info \n%s\n", message)
   233  }
   234  
   235  func (ui *CommandlineUI) OnApprovedTx(tx ethapi.SignTransactionResult) {
   236  	fmt.Printf("Transaction signed:\n ")
   237  	if jsn, err := json.MarshalIndent(tx.Tx, "  ", "  "); err != nil {
   238  		fmt.Printf("WARN: marshalling error %v\n", err)
   239  	} else {
   240  		fmt.Println(string(jsn))
   241  	}
   242  }
   243  
   244  func (ui *CommandlineUI) OnSignerStartup(info StartupInfo) {
   245  
   246  	fmt.Printf("------- Signer info -------\n")
   247  	for k, v := range info.Info {
   248  		fmt.Printf("* %v : %v\n", k, v)
   249  	}
   250  }