github.com/aswedchain/aswed@v1.0.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  	"encoding/json"
    22  	"fmt"
    23  	"os"
    24  	"strings"
    25  	"sync"
    26  
    27  	"github.com/aswedchain/aswed/common/hexutil"
    28  	"github.com/aswedchain/aswed/console/prompt"
    29  	"github.com/aswedchain/aswed/internal/ethapi"
    30  	"github.com/aswedchain/aswed/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  
    63  	fmt.Printf("## %s\n\n%s\n", info.Title, info.Prompt)
    64  	defer fmt.Println("-----------------------")
    65  	if info.IsPassword {
    66  		text, err := prompt.Stdin.PromptPassword("> ")
    67  		if err != nil {
    68  			log.Error("Failed to read password", "error", err)
    69  			return UserInputResponse{}, err
    70  		}
    71  		return UserInputResponse{text}, nil
    72  	}
    73  	text := ui.readString()
    74  	return UserInputResponse{text}, nil
    75  }
    76  
    77  // confirm returns true if user enters 'Yes', otherwise false
    78  func (ui *CommandlineUI) confirm() bool {
    79  	fmt.Printf("Approve? [y/N]:\n")
    80  	if ui.readString() == "y" {
    81  		return true
    82  	}
    83  	fmt.Println("-----------------------")
    84  	return false
    85  }
    86  
    87  // sanitize quotes and truncates 'txt' if longer than 'limit'. If truncated,
    88  // and ellipsis is added after the quoted string
    89  func sanitize(txt string, limit int) string {
    90  	if len(txt) > limit {
    91  		return fmt.Sprintf("%q...", txt[:limit])
    92  	}
    93  	return fmt.Sprintf("%q", txt)
    94  }
    95  
    96  func showMetadata(metadata Metadata) {
    97  	fmt.Printf("Request context:\n\t%v -> %v -> %v\n", metadata.Remote, metadata.Scheme, metadata.Local)
    98  	fmt.Printf("\nAdditional HTTP header data, provided by the external caller:\n")
    99  	fmt.Printf("\tUser-Agent: %v\n\tOrigin: %v\n", sanitize(metadata.UserAgent, 200), sanitize(metadata.Origin, 100))
   100  }
   101  
   102  // ApproveTx prompt the user for confirmation to request to sign Transaction
   103  func (ui *CommandlineUI) ApproveTx(request *SignTxRequest) (SignTxResponse, error) {
   104  	ui.mu.Lock()
   105  	defer ui.mu.Unlock()
   106  	weival := request.Transaction.Value.ToInt()
   107  	fmt.Printf("--------- Transaction request-------------\n")
   108  	if to := request.Transaction.To; to != nil {
   109  		fmt.Printf("to:    %v\n", to.Original())
   110  		if !to.ValidChecksum() {
   111  			fmt.Printf("\nWARNING: Invalid checksum on to-address!\n\n")
   112  		}
   113  	} else {
   114  		fmt.Printf("to:    <contact creation>\n")
   115  	}
   116  	fmt.Printf("from:     %v\n", request.Transaction.From.String())
   117  	fmt.Printf("value:    %v wei\n", weival)
   118  	fmt.Printf("gas:      %v (%v)\n", request.Transaction.Gas, uint64(request.Transaction.Gas))
   119  	fmt.Printf("gasprice: %v wei\n", request.Transaction.GasPrice.ToInt())
   120  	fmt.Printf("nonce:    %v (%v)\n", request.Transaction.Nonce, uint64(request.Transaction.Nonce))
   121  	if request.Transaction.Data != nil {
   122  		d := *request.Transaction.Data
   123  		if len(d) > 0 {
   124  			fmt.Printf("data:     %v\n", hexutil.Encode(d))
   125  		}
   126  	}
   127  	if request.Callinfo != nil {
   128  		fmt.Printf("\nTransaction validation:\n")
   129  		for _, m := range request.Callinfo {
   130  			fmt.Printf("  * %s : %s\n", m.Typ, m.Message)
   131  		}
   132  		fmt.Println()
   133  
   134  	}
   135  	fmt.Printf("\n")
   136  	showMetadata(request.Meta)
   137  	fmt.Printf("-------------------------------------------\n")
   138  	if !ui.confirm() {
   139  		return SignTxResponse{request.Transaction, false}, nil
   140  	}
   141  	return SignTxResponse{request.Transaction, true}, nil
   142  }
   143  
   144  // ApproveSignData prompt the user for confirmation to request to sign data
   145  func (ui *CommandlineUI) ApproveSignData(request *SignDataRequest) (SignDataResponse, error) {
   146  	ui.mu.Lock()
   147  	defer ui.mu.Unlock()
   148  
   149  	fmt.Printf("-------- Sign data request--------------\n")
   150  	fmt.Printf("Account:  %s\n", request.Address.String())
   151  	if len(request.Callinfo) != 0 {
   152  		fmt.Printf("\nValidation messages:\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("messages:\n")
   159  	for _, nvt := range request.Messages {
   160  		fmt.Printf("\u00a0\u00a0%v\n", strings.TrimSpace(nvt.Pprint(1)))
   161  	}
   162  	fmt.Printf("raw data:  \n\t%q\n", request.Rawdata)
   163  	fmt.Printf("data hash:  %v\n", request.Hash)
   164  	fmt.Printf("-------------------------------------------\n")
   165  	showMetadata(request.Meta)
   166  	if !ui.confirm() {
   167  		return SignDataResponse{false}, nil
   168  	}
   169  	return SignDataResponse{true}, nil
   170  }
   171  
   172  // ApproveListing prompt the user for confirmation to list accounts
   173  // the list of accounts to list can be modified by the UI
   174  func (ui *CommandlineUI) ApproveListing(request *ListRequest) (ListResponse, error) {
   175  	ui.mu.Lock()
   176  	defer ui.mu.Unlock()
   177  
   178  	fmt.Printf("-------- List Account request--------------\n")
   179  	fmt.Printf("A request has been made to list all accounts. \n")
   180  	fmt.Printf("You can select which accounts the caller can see\n")
   181  	for _, account := range request.Accounts {
   182  		fmt.Printf("  [x] %v\n", account.Address.Hex())
   183  		fmt.Printf("    URL: %v\n", account.URL)
   184  	}
   185  	fmt.Printf("-------------------------------------------\n")
   186  	showMetadata(request.Meta)
   187  	if !ui.confirm() {
   188  		return ListResponse{nil}, nil
   189  	}
   190  	return ListResponse{request.Accounts}, nil
   191  }
   192  
   193  // ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller
   194  func (ui *CommandlineUI) ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) {
   195  
   196  	ui.mu.Lock()
   197  	defer ui.mu.Unlock()
   198  
   199  	fmt.Printf("-------- New Account request--------------\n\n")
   200  	fmt.Printf("A request has been made to create a new account. \n")
   201  	fmt.Printf("Approving this operation means that a new account is created,\n")
   202  	fmt.Printf("and the address is returned to the external caller\n\n")
   203  	showMetadata(request.Meta)
   204  	if !ui.confirm() {
   205  		return NewAccountResponse{false}, nil
   206  	}
   207  	return NewAccountResponse{true}, nil
   208  }
   209  
   210  // ShowError displays error message to user
   211  func (ui *CommandlineUI) ShowError(message string) {
   212  	fmt.Printf("## Error \n%s\n", message)
   213  	fmt.Printf("-------------------------------------------\n")
   214  }
   215  
   216  // ShowInfo displays info message to user
   217  func (ui *CommandlineUI) ShowInfo(message string) {
   218  	fmt.Printf("## Info \n%s\n", message)
   219  }
   220  
   221  func (ui *CommandlineUI) OnApprovedTx(tx ethapi.SignTransactionResult) {
   222  	fmt.Printf("Transaction signed:\n ")
   223  	if jsn, err := json.MarshalIndent(tx.Tx, "  ", "  "); err != nil {
   224  		fmt.Printf("WARN: marshalling error %v\n", err)
   225  	} else {
   226  		fmt.Println(string(jsn))
   227  	}
   228  }
   229  
   230  func (ui *CommandlineUI) OnSignerStartup(info StartupInfo) {
   231  
   232  	fmt.Printf("------- Signer info -------\n")
   233  	for k, v := range info.Info {
   234  		fmt.Printf("* %v : %v\n", k, v)
   235  	}
   236  }