gitlab.com/yannislg/go-pulse@v0.0.0-20210722055913-a3e24e95638d/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  func (ui *CommandlineUI) OnInputRequired(info UserInputRequest) (UserInputResponse, error) {
    62  
    63  	fmt.Printf("## %s\n\n%s\n", info.Title, info.Prompt)
    64  	if info.IsPassword {
    65  		fmt.Printf("> ")
    66  		text, err := terminal.ReadPassword(int(os.Stdin.Fd()))
    67  		if err != nil {
    68  			log.Error("Failed to read password", "err", err)
    69  		}
    70  		fmt.Println("-----------------------")
    71  		return UserInputResponse{string(text)}, err
    72  	}
    73  	text := ui.readString()
    74  	fmt.Println("-----------------------")
    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  func showMetadata(metadata Metadata) {
    89  	fmt.Printf("Request context:\n\t%v -> %v -> %v\n", metadata.Remote, metadata.Scheme, metadata.Local)
    90  	fmt.Printf("\nAdditional HTTP header data, provided by the external caller:\n")
    91  	fmt.Printf("\tUser-Agent: %v\n\tOrigin: %v\n", metadata.UserAgent, metadata.Origin)
    92  }
    93  
    94  // ApproveTx prompt the user for confirmation to request to sign Transaction
    95  func (ui *CommandlineUI) ApproveTx(request *SignTxRequest) (SignTxResponse, error) {
    96  	ui.mu.Lock()
    97  	defer ui.mu.Unlock()
    98  	weival := request.Transaction.Value.ToInt()
    99  	fmt.Printf("--------- Transaction request-------------\n")
   100  	if to := request.Transaction.To; to != nil {
   101  		fmt.Printf("to:    %v\n", to.Original())
   102  		if !to.ValidChecksum() {
   103  			fmt.Printf("\nWARNING: Invalid checksum on to-address!\n\n")
   104  		}
   105  	} else {
   106  		fmt.Printf("to:    <contact creation>\n")
   107  	}
   108  	fmt.Printf("from:     %v\n", request.Transaction.From.String())
   109  	fmt.Printf("value:    %v wei\n", weival)
   110  	fmt.Printf("gas:      %v (%v)\n", request.Transaction.Gas, uint64(request.Transaction.Gas))
   111  	fmt.Printf("gasprice: %v wei\n", request.Transaction.GasPrice.ToInt())
   112  	fmt.Printf("nonce:    %v (%v)\n", request.Transaction.Nonce, uint64(request.Transaction.Nonce))
   113  	if request.Transaction.Data != nil {
   114  		d := *request.Transaction.Data
   115  		if len(d) > 0 {
   116  
   117  			fmt.Printf("data:     %v\n", hexutil.Encode(d))
   118  		}
   119  	}
   120  	if request.Callinfo != nil {
   121  		fmt.Printf("\nTransaction validation:\n")
   122  		for _, m := range request.Callinfo {
   123  			fmt.Printf("  * %s : %s\n", m.Typ, m.Message)
   124  		}
   125  		fmt.Println()
   126  
   127  	}
   128  	fmt.Printf("\n")
   129  	showMetadata(request.Meta)
   130  	fmt.Printf("-------------------------------------------\n")
   131  	if !ui.confirm() {
   132  		return SignTxResponse{request.Transaction, false}, nil
   133  	}
   134  	return SignTxResponse{request.Transaction, true}, nil
   135  }
   136  
   137  // ApproveSignData prompt the user for confirmation to request to sign data
   138  func (ui *CommandlineUI) ApproveSignData(request *SignDataRequest) (SignDataResponse, error) {
   139  	ui.mu.Lock()
   140  	defer ui.mu.Unlock()
   141  
   142  	fmt.Printf("-------- Sign data request--------------\n")
   143  	fmt.Printf("Account:  %s\n", request.Address.String())
   144  	fmt.Printf("messages:\n")
   145  	for _, nvt := range request.Messages {
   146  		fmt.Printf("\u00a0\u00a0%v\n", strings.TrimSpace(nvt.Pprint(1)))
   147  	}
   148  	fmt.Printf("raw data:  \n%q\n", request.Rawdata)
   149  	fmt.Printf("data hash:  %v\n", request.Hash)
   150  	fmt.Printf("-------------------------------------------\n")
   151  	showMetadata(request.Meta)
   152  	if !ui.confirm() {
   153  		return SignDataResponse{false}, nil
   154  	}
   155  	return SignDataResponse{true}, nil
   156  }
   157  
   158  // ApproveListing prompt the user for confirmation to list accounts
   159  // the list of accounts to list can be modified by the UI
   160  func (ui *CommandlineUI) ApproveListing(request *ListRequest) (ListResponse, error) {
   161  	ui.mu.Lock()
   162  	defer ui.mu.Unlock()
   163  
   164  	fmt.Printf("-------- List Account request--------------\n")
   165  	fmt.Printf("A request has been made to list all accounts. \n")
   166  	fmt.Printf("You can select which accounts the caller can see\n")
   167  	for _, account := range request.Accounts {
   168  		fmt.Printf("  [x] %v\n", account.Address.Hex())
   169  		fmt.Printf("    URL: %v\n", account.URL)
   170  	}
   171  	fmt.Printf("-------------------------------------------\n")
   172  	showMetadata(request.Meta)
   173  	if !ui.confirm() {
   174  		return ListResponse{nil}, nil
   175  	}
   176  	return ListResponse{request.Accounts}, nil
   177  }
   178  
   179  // ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller
   180  func (ui *CommandlineUI) ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) {
   181  
   182  	ui.mu.Lock()
   183  	defer ui.mu.Unlock()
   184  
   185  	fmt.Printf("-------- New Account request--------------\n\n")
   186  	fmt.Printf("A request has been made to create a new account. \n")
   187  	fmt.Printf("Approving this operation means that a new account is created,\n")
   188  	fmt.Printf("and the address is returned to the external caller\n\n")
   189  	showMetadata(request.Meta)
   190  	if !ui.confirm() {
   191  		return NewAccountResponse{false}, nil
   192  	}
   193  	return NewAccountResponse{true}, nil
   194  }
   195  
   196  // ShowError displays error message to user
   197  func (ui *CommandlineUI) ShowError(message string) {
   198  	fmt.Printf("## Error \n%s\n", message)
   199  	fmt.Printf("-------------------------------------------\n")
   200  }
   201  
   202  // ShowInfo displays info message to user
   203  func (ui *CommandlineUI) ShowInfo(message string) {
   204  	fmt.Printf("## Info \n%s\n", message)
   205  }
   206  
   207  func (ui *CommandlineUI) OnApprovedTx(tx ethapi.SignTransactionResult) {
   208  	fmt.Printf("Transaction signed:\n ")
   209  	if jsn, err := json.MarshalIndent(tx.Tx, "  ", "  "); err != nil {
   210  		fmt.Printf("WARN: marshalling error %v\n", err)
   211  	} else {
   212  		fmt.Println(string(jsn))
   213  	}
   214  }
   215  
   216  func (ui *CommandlineUI) OnSignerStartup(info StartupInfo) {
   217  
   218  	fmt.Printf("------- Signer info -------\n")
   219  	for k, v := range info.Info {
   220  		fmt.Printf("* %v : %v\n", k, v)
   221  	}
   222  }