github.com/bcnmy/go-ethereum@v1.10.27/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/console/prompt"
    29  	"github.com/ethereum/go-ethereum/internal/ethapi"
    30  	"github.com/ethereum/go-ethereum/log"
    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  func (ui *CommandlineUI) OnInputRequired(info UserInputRequest) (UserInputResponse, error) {
    62  	fmt.Printf("## %s\n\n%s\n", info.Title, info.Prompt)
    63  	defer fmt.Println("-----------------------")
    64  	if info.IsPassword {
    65  		text, err := prompt.Stdin.PromptPassword("> ")
    66  		if err != nil {
    67  			log.Error("Failed to read password", "error", err)
    68  			return UserInputResponse{}, err
    69  		}
    70  		return UserInputResponse{text}, nil
    71  	}
    72  	text := ui.readString()
    73  	return UserInputResponse{text}, nil
    74  }
    75  
    76  // confirm returns true if user enters 'Yes', otherwise false
    77  func (ui *CommandlineUI) confirm() bool {
    78  	fmt.Printf("Approve? [y/N]:\n")
    79  	if ui.readString() == "y" {
    80  		return true
    81  	}
    82  	fmt.Println("-----------------------")
    83  	return false
    84  }
    85  
    86  // sanitize quotes and truncates 'txt' if longer than 'limit'. If truncated,
    87  // and ellipsis is added after the quoted string
    88  func sanitize(txt string, limit int) string {
    89  	if len(txt) > limit {
    90  		return fmt.Sprintf("%q...", txt[:limit])
    91  	}
    92  	return fmt.Sprintf("%q", txt)
    93  }
    94  
    95  func showMetadata(metadata Metadata) {
    96  	fmt.Printf("Request context:\n\t%v -> %v -> %v\n", metadata.Remote, metadata.Scheme, metadata.Local)
    97  	fmt.Printf("\nAdditional HTTP header data, provided by the external caller:\n")
    98  	fmt.Printf("\tUser-Agent: %v\n\tOrigin: %v\n", sanitize(metadata.UserAgent, 200), sanitize(metadata.Origin, 100))
    99  }
   100  
   101  // ApproveTx prompt the user for confirmation to request to sign Transaction
   102  func (ui *CommandlineUI) ApproveTx(request *SignTxRequest) (SignTxResponse, error) {
   103  	ui.mu.Lock()
   104  	defer ui.mu.Unlock()
   105  	weival := request.Transaction.Value.ToInt()
   106  	fmt.Printf("--------- Transaction request-------------\n")
   107  	if to := request.Transaction.To; to != nil {
   108  		fmt.Printf("to:    %v\n", to.Original())
   109  		if !to.ValidChecksum() {
   110  			fmt.Printf("\nWARNING: Invalid checksum on to-address!\n\n")
   111  		}
   112  	} else {
   113  		fmt.Printf("to:    <contact creation>\n")
   114  	}
   115  	fmt.Printf("from:               %v\n", request.Transaction.From.String())
   116  	fmt.Printf("value:              %v wei\n", weival)
   117  	fmt.Printf("gas:                %v (%v)\n", request.Transaction.Gas, uint64(request.Transaction.Gas))
   118  	if request.Transaction.MaxFeePerGas != nil {
   119  		fmt.Printf("maxFeePerGas:          %v wei\n", request.Transaction.MaxFeePerGas.ToInt())
   120  		fmt.Printf("maxPriorityFeePerGas:  %v wei\n", request.Transaction.MaxPriorityFeePerGas.ToInt())
   121  	} else {
   122  		fmt.Printf("gasprice: %v wei\n", request.Transaction.GasPrice.ToInt())
   123  	}
   124  	fmt.Printf("nonce:    %v (%v)\n", request.Transaction.Nonce, uint64(request.Transaction.Nonce))
   125  	if chainId := request.Transaction.ChainID; chainId != nil {
   126  		fmt.Printf("chainid:  %v\n", chainId)
   127  	}
   128  	if list := request.Transaction.AccessList; list != nil {
   129  		fmt.Printf("Accesslist\n")
   130  		for i, el := range *list {
   131  			fmt.Printf(" %d. %v\n", i, el.Address)
   132  			for j, slot := range el.StorageKeys {
   133  				fmt.Printf("   %d. %v\n", j, slot)
   134  			}
   135  		}
   136  	}
   137  	if request.Transaction.Data != nil {
   138  		d := *request.Transaction.Data
   139  		if len(d) > 0 {
   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  	fmt.Printf("\n")
   151  	showMetadata(request.Meta)
   152  	fmt.Printf("-------------------------------------------\n")
   153  	if !ui.confirm() {
   154  		return SignTxResponse{request.Transaction, false}, nil
   155  	}
   156  	return SignTxResponse{request.Transaction, true}, nil
   157  }
   158  
   159  // ApproveSignData prompt the user for confirmation to request to sign data
   160  func (ui *CommandlineUI) ApproveSignData(request *SignDataRequest) (SignDataResponse, error) {
   161  	ui.mu.Lock()
   162  	defer ui.mu.Unlock()
   163  
   164  	fmt.Printf("-------- Sign data request--------------\n")
   165  	fmt.Printf("Account:  %s\n", request.Address.String())
   166  	if len(request.Callinfo) != 0 {
   167  		fmt.Printf("\nValidation messages:\n")
   168  		for _, m := range request.Callinfo {
   169  			fmt.Printf("  * %s : %s\n", m.Typ, m.Message)
   170  		}
   171  		fmt.Println()
   172  	}
   173  	fmt.Printf("messages:\n")
   174  	for _, nvt := range request.Messages {
   175  		fmt.Printf("\u00a0\u00a0%v\n", strings.TrimSpace(nvt.Pprint(1)))
   176  	}
   177  	fmt.Printf("raw data:  \n\t%q\n", request.Rawdata)
   178  	fmt.Printf("data hash:  %v\n", request.Hash)
   179  	fmt.Printf("-------------------------------------------\n")
   180  	showMetadata(request.Meta)
   181  	if !ui.confirm() {
   182  		return SignDataResponse{false}, nil
   183  	}
   184  	return SignDataResponse{true}, nil
   185  }
   186  
   187  // ApproveListing prompt the user for confirmation to list accounts
   188  // the list of accounts to list can be modified by the UI
   189  func (ui *CommandlineUI) ApproveListing(request *ListRequest) (ListResponse, error) {
   190  	ui.mu.Lock()
   191  	defer ui.mu.Unlock()
   192  
   193  	fmt.Printf("-------- List Account request--------------\n")
   194  	fmt.Printf("A request has been made to list all accounts. \n")
   195  	fmt.Printf("You can select which accounts the caller can see\n")
   196  	for _, account := range request.Accounts {
   197  		fmt.Printf("  [x] %v\n", account.Address.Hex())
   198  		fmt.Printf("    URL: %v\n", account.URL)
   199  	}
   200  	fmt.Printf("-------------------------------------------\n")
   201  	showMetadata(request.Meta)
   202  	if !ui.confirm() {
   203  		return ListResponse{nil}, nil
   204  	}
   205  	return ListResponse{request.Accounts}, nil
   206  }
   207  
   208  // ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller
   209  func (ui *CommandlineUI) ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) {
   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  	fmt.Printf("------- Signer info -------\n")
   246  	for k, v := range info.Info {
   247  		fmt.Printf("* %v : %v\n", k, v)
   248  	}
   249  }