github.com/ethereum/go-ethereum@v1.16.1/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  	"context"
    22  	"encoding/json"
    23  	"fmt"
    24  	"os"
    25  	"strings"
    26  	"sync"
    27  
    28  	"github.com/ethereum/go-ethereum/common/hexutil"
    29  	"github.com/ethereum/go-ethereum/console/prompt"
    30  	"github.com/ethereum/go-ethereum/internal/ethapi"
    31  	"github.com/ethereum/go-ethereum/log"
    32  )
    33  
    34  type CommandlineUI struct {
    35  	in  *bufio.Reader
    36  	mu  sync.Mutex
    37  	api *UIServerAPI
    38  }
    39  
    40  func NewCommandlineUI() *CommandlineUI {
    41  	return &CommandlineUI{in: bufio.NewReader(os.Stdin)}
    42  }
    43  
    44  func (ui *CommandlineUI) RegisterUIServer(api *UIServerAPI) {
    45  	ui.api = api
    46  }
    47  
    48  // readString reads a single line from stdin, trimming if from spaces, enforcing
    49  // non-emptyness.
    50  func (ui *CommandlineUI) readString() string {
    51  	for {
    52  		fmt.Printf("> ")
    53  		text, err := ui.in.ReadString('\n')
    54  		if err != nil {
    55  			log.Crit("Failed to read user input", "err", err)
    56  		}
    57  		if text = strings.TrimSpace(text); text != "" {
    58  			return text
    59  		}
    60  	}
    61  }
    62  
    63  func (ui *CommandlineUI) OnInputRequired(info UserInputRequest) (UserInputResponse, error) {
    64  	fmt.Printf("## %s\n\n%s\n", info.Title, info.Prompt)
    65  	defer fmt.Println("-----------------------")
    66  	if info.IsPassword {
    67  		text, err := prompt.Stdin.PromptPassword("> ")
    68  		if err != nil {
    69  			log.Error("Failed to read password", "error", err)
    70  			return UserInputResponse{}, err
    71  		}
    72  		return UserInputResponse{text}, nil
    73  	}
    74  	text := ui.readString()
    75  	return UserInputResponse{text}, nil
    76  }
    77  
    78  // confirm returns true if user enters 'Yes', otherwise false
    79  func (ui *CommandlineUI) confirm() bool {
    80  	fmt.Printf("Approve? [y/N]:\n")
    81  	if ui.readString() == "y" {
    82  		return true
    83  	}
    84  	fmt.Println("-----------------------")
    85  	return false
    86  }
    87  
    88  // sanitize quotes and truncates 'txt' if longer than 'limit'. If truncated,
    89  // and ellipsis is added after the quoted string
    90  func sanitize(txt string, limit int) string {
    91  	if len(txt) > limit {
    92  		return fmt.Sprintf("%q...", txt[:limit])
    93  	}
    94  	return fmt.Sprintf("%q", txt)
    95  }
    96  
    97  func showMetadata(metadata Metadata) {
    98  	fmt.Printf("Request context:\n\t%v -> %v -> %v\n", metadata.Remote, metadata.Scheme, metadata.Local)
    99  	fmt.Printf("\nAdditional HTTP header data, provided by the external caller:\n")
   100  	fmt.Printf("\tUser-Agent: %v\n\tOrigin: %v\n", sanitize(metadata.UserAgent, 200), sanitize(metadata.Origin, 100))
   101  }
   102  
   103  // ApproveTx prompt the user for confirmation to request to sign Transaction
   104  func (ui *CommandlineUI) ApproveTx(request *SignTxRequest) (SignTxResponse, error) {
   105  	ui.mu.Lock()
   106  	defer ui.mu.Unlock()
   107  	weival := request.Transaction.Value.ToInt()
   108  	fmt.Printf("--------- Transaction request-------------\n")
   109  	if to := request.Transaction.To; to != nil {
   110  		fmt.Printf("to:    %v\n", to.Original())
   111  		if !to.ValidChecksum() {
   112  			fmt.Printf("\nWARNING: Invalid checksum on to-address!\n\n")
   113  		}
   114  	} else {
   115  		fmt.Printf("to:    <contact creation>\n")
   116  	}
   117  	fmt.Printf("from:               %v\n", request.Transaction.From.String())
   118  	fmt.Printf("value:              %v wei\n", weival)
   119  	fmt.Printf("gas:                %v (%v)\n", request.Transaction.Gas, uint64(request.Transaction.Gas))
   120  	if request.Transaction.MaxFeePerGas != nil {
   121  		fmt.Printf("maxFeePerGas:          %v wei\n", request.Transaction.MaxFeePerGas.ToInt())
   122  		fmt.Printf("maxPriorityFeePerGas:  %v wei\n", request.Transaction.MaxPriorityFeePerGas.ToInt())
   123  	} else {
   124  		fmt.Printf("gasprice: %v wei\n", request.Transaction.GasPrice.ToInt())
   125  	}
   126  	fmt.Printf("nonce:    %v (%v)\n", request.Transaction.Nonce, uint64(request.Transaction.Nonce))
   127  	if chainId := request.Transaction.ChainID; chainId != nil {
   128  		fmt.Printf("chainid:  %v\n", chainId)
   129  	}
   130  	if list := request.Transaction.AccessList; list != nil {
   131  		fmt.Printf("Accesslist:\n")
   132  		for i, el := range *list {
   133  			fmt.Printf(" %d. %v\n", i, el.Address)
   134  			for j, slot := range el.StorageKeys {
   135  				fmt.Printf("   %d. %v\n", j, slot)
   136  			}
   137  		}
   138  	}
   139  	if len(request.Transaction.BlobHashes) > 0 {
   140  		fmt.Printf("Blob hashes:\n")
   141  		for _, bh := range request.Transaction.BlobHashes {
   142  			fmt.Printf("   %v\n", bh)
   143  		}
   144  	}
   145  	if request.Transaction.Data != nil {
   146  		d := *request.Transaction.Data
   147  		if len(d) > 0 {
   148  			fmt.Printf("data:     %v\n", hexutil.Encode(d))
   149  		}
   150  	}
   151  	if request.Callinfo != nil {
   152  		fmt.Printf("\nTransaction validation:\n")
   153  		for _, m := range request.Callinfo {
   154  			fmt.Printf("  * %s : %s\n", m.Typ, m.Message)
   155  		}
   156  		fmt.Println()
   157  	}
   158  	fmt.Printf("\n")
   159  	showMetadata(request.Meta)
   160  	fmt.Printf("-------------------------------------------\n")
   161  	if !ui.confirm() {
   162  		return SignTxResponse{request.Transaction, false}, nil
   163  	}
   164  	return SignTxResponse{request.Transaction, true}, nil
   165  }
   166  
   167  // ApproveSignData prompt the user for confirmation to request to sign data
   168  func (ui *CommandlineUI) ApproveSignData(request *SignDataRequest) (SignDataResponse, error) {
   169  	ui.mu.Lock()
   170  	defer ui.mu.Unlock()
   171  
   172  	fmt.Printf("-------- Sign data request--------------\n")
   173  	fmt.Printf("Account:  %s\n", request.Address.String())
   174  	if len(request.Callinfo) != 0 {
   175  		fmt.Printf("\nValidation messages:\n")
   176  		for _, m := range request.Callinfo {
   177  			fmt.Printf("  * %s : %s\n", m.Typ, m.Message)
   178  		}
   179  		fmt.Println()
   180  	}
   181  	fmt.Printf("messages:\n")
   182  	for _, nvt := range request.Messages {
   183  		fmt.Printf("\u00a0\u00a0%v\n", strings.TrimSpace(nvt.Pprint(1)))
   184  	}
   185  	fmt.Printf("raw data:  \n\t%q\n", request.Rawdata)
   186  	fmt.Printf("data hash:  %v\n", request.Hash)
   187  	fmt.Printf("-------------------------------------------\n")
   188  	showMetadata(request.Meta)
   189  	if !ui.confirm() {
   190  		return SignDataResponse{false}, nil
   191  	}
   192  	return SignDataResponse{true}, nil
   193  }
   194  
   195  // ApproveListing prompt the user for confirmation to list accounts
   196  // the list of accounts to list can be modified by the UI
   197  func (ui *CommandlineUI) ApproveListing(request *ListRequest) (ListResponse, error) {
   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  	}
   208  	fmt.Printf("-------------------------------------------\n")
   209  	showMetadata(request.Meta)
   210  	if !ui.confirm() {
   211  		return ListResponse{nil}, nil
   212  	}
   213  	return ListResponse{request.Accounts}, nil
   214  }
   215  
   216  // ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller
   217  func (ui *CommandlineUI) ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) {
   218  	ui.mu.Lock()
   219  	defer ui.mu.Unlock()
   220  
   221  	fmt.Printf("-------- New Account request--------------\n\n")
   222  	fmt.Printf("A request has been made to create a new account. \n")
   223  	fmt.Printf("Approving this operation means that a new account is created,\n")
   224  	fmt.Printf("and the address is returned to the external caller\n\n")
   225  	showMetadata(request.Meta)
   226  	if !ui.confirm() {
   227  		return NewAccountResponse{false}, nil
   228  	}
   229  	return NewAccountResponse{true}, nil
   230  }
   231  
   232  // ShowError displays error message to user
   233  func (ui *CommandlineUI) ShowError(message string) {
   234  	fmt.Printf("## Error \n%s\n", message)
   235  	fmt.Printf("-------------------------------------------\n")
   236  }
   237  
   238  // ShowInfo displays info message to user
   239  func (ui *CommandlineUI) ShowInfo(message string) {
   240  	fmt.Printf("## Info \n%s\n", message)
   241  }
   242  
   243  func (ui *CommandlineUI) OnApprovedTx(tx ethapi.SignTransactionResult) {
   244  	fmt.Printf("Transaction signed:\n ")
   245  	if jsn, err := json.MarshalIndent(tx.Tx, "  ", "  "); err != nil {
   246  		fmt.Printf("WARN: marshalling error %v\n", err)
   247  	} else {
   248  		fmt.Println(string(jsn))
   249  	}
   250  }
   251  
   252  func (ui *CommandlineUI) showAccounts() {
   253  	accounts, err := ui.api.ListAccounts(context.Background())
   254  	if err != nil {
   255  		log.Error("Error listing accounts", "err", err)
   256  		return
   257  	}
   258  	if len(accounts) == 0 {
   259  		fmt.Print("No accounts found\n")
   260  		return
   261  	}
   262  	var msg string
   263  	var out = new(strings.Builder)
   264  	if limit := 20; len(accounts) > limit {
   265  		msg = fmt.Sprintf("\nFirst %d accounts listed (%d more available).\n", limit, len(accounts)-limit)
   266  		accounts = accounts[:limit]
   267  	}
   268  	fmt.Fprint(out, "\n------- Available accounts -------\n")
   269  	for i, account := range accounts {
   270  		fmt.Fprintf(out, "%d. %s at %s\n", i, account.Address, account.URL)
   271  	}
   272  	fmt.Print(out.String(), msg)
   273  }
   274  
   275  func (ui *CommandlineUI) OnSignerStartup(info StartupInfo) {
   276  	fmt.Print("\n------- Signer info -------\n")
   277  	for k, v := range info.Info {
   278  		fmt.Printf("* %v : %v\n", k, v)
   279  	}
   280  	go ui.showAccounts()
   281  }