github.com/core-coin/go-core/v2@v2.1.9/signer/core/cliui.go (about)

     1  // Copyright 2018 by the Authors
     2  // This file is part of the go-core library.
     3  //
     4  // The go-core 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-core 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-core 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/core-coin/go-core/v2/internal/xcbapi"
    28  
    29  	"github.com/core-coin/go-core/v2/common/hexutil"
    30  	"github.com/core-coin/go-core/v2/console/prompt"
    31  	"github.com/core-coin/go-core/v2/log"
    32  )
    33  
    34  type CommandlineUI struct {
    35  	in *bufio.Reader
    36  	mu sync.Mutex
    37  }
    38  
    39  func NewCommandlineUI() *CommandlineUI {
    40  	return &CommandlineUI{in: bufio.NewReader(os.Stdin)}
    41  }
    42  
    43  func (ui *CommandlineUI) RegisterUIServer(api *UIServerAPI) {
    44  	// noop
    45  }
    46  
    47  // readString reads a single line from stdin, trimming if from spaces, enforcing
    48  // non-emptyness.
    49  func (ui *CommandlineUI) readString() string {
    50  	for {
    51  		fmt.Printf("> ")
    52  		text, err := ui.in.ReadString('\n')
    53  		if err != nil {
    54  			log.Crit("Failed to read user input", "err", err)
    55  		}
    56  		if text = strings.TrimSpace(text); text != "" {
    57  			return text
    58  		}
    59  	}
    60  }
    61  
    62  func (ui *CommandlineUI) OnInputRequired(info UserInputRequest) (UserInputResponse, error) {
    63  
    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  	oreval := 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.String())
   111  	} else {
   112  		fmt.Printf("to:    <contact creation>\n")
   113  	}
   114  	fmt.Printf("from:     %v\n", request.Transaction.From.String())
   115  	fmt.Printf("value:    %v ore\n", oreval)
   116  	fmt.Printf("energy:      %v (%v)\n", request.Transaction.Energy, uint64(request.Transaction.Energy))
   117  	fmt.Printf("energyprice: %v ore\n", request.Transaction.EnergyPrice.ToInt())
   118  	fmt.Printf("nonce:    %v (%v)\n", request.Transaction.Nonce, uint64(request.Transaction.Nonce))
   119  	if request.Transaction.Data != nil {
   120  		d := *request.Transaction.Data
   121  		if len(d) > 0 {
   122  			fmt.Printf("data:     %v\n", hexutil.Encode(d))
   123  		}
   124  	}
   125  	if request.Callinfo != nil {
   126  		fmt.Printf("\nTransaction validation:\n")
   127  		for _, m := range request.Callinfo {
   128  			fmt.Printf("  * %s : %s\n", m.Typ, m.Message)
   129  		}
   130  		fmt.Println()
   131  
   132  	}
   133  	fmt.Printf("\n")
   134  	showMetadata(request.Meta)
   135  	fmt.Printf("-------------------------------------------\n")
   136  	if !ui.confirm() {
   137  		return SignTxResponse{request.Transaction, false}, nil
   138  	}
   139  	return SignTxResponse{request.Transaction, true}, nil
   140  }
   141  
   142  // ApproveSignData prompt the user for confirmation to request to sign data
   143  func (ui *CommandlineUI) ApproveSignData(request *SignDataRequest) (SignDataResponse, error) {
   144  	ui.mu.Lock()
   145  	defer ui.mu.Unlock()
   146  
   147  	fmt.Printf("-------- Sign data request--------------\n")
   148  	fmt.Printf("Account:  %s\n", request.Address.String())
   149  	if len(request.Callinfo) != 0 {
   150  		fmt.Printf("\nValidation messages:\n")
   151  		for _, m := range request.Callinfo {
   152  			fmt.Printf("  * %s : %s\n", m.Typ, m.Message)
   153  		}
   154  		fmt.Println()
   155  	}
   156  	fmt.Printf("messages:\n")
   157  	for _, nvt := range request.Messages {
   158  		fmt.Printf("\u00a0\u00a0%v\n", strings.TrimSpace(nvt.Pprint(1)))
   159  	}
   160  	fmt.Printf("raw data:  \n\t%q\n", request.Rawdata)
   161  	fmt.Printf("data hash:  %v\n", request.Hash)
   162  	fmt.Printf("-------------------------------------------\n")
   163  	showMetadata(request.Meta)
   164  	if !ui.confirm() {
   165  		return SignDataResponse{false}, nil
   166  	}
   167  	return SignDataResponse{true}, nil
   168  }
   169  
   170  // ApproveListing prompt the user for confirmation to list accounts
   171  // the list of accounts to list can be modified by the UI
   172  func (ui *CommandlineUI) ApproveListing(request *ListRequest) (ListResponse, error) {
   173  	ui.mu.Lock()
   174  	defer ui.mu.Unlock()
   175  
   176  	fmt.Printf("-------- List Account request--------------\n")
   177  	fmt.Printf("A request has been made to list all accounts. \n")
   178  	fmt.Printf("You can select which accounts the caller can see\n")
   179  	for _, account := range request.Accounts {
   180  		fmt.Printf("  [x] %v\n", account.Address.Hex())
   181  		fmt.Printf("    URL: %v\n", account.URL)
   182  	}
   183  	fmt.Printf("-------------------------------------------\n")
   184  	showMetadata(request.Meta)
   185  	if !ui.confirm() {
   186  		return ListResponse{nil}, nil
   187  	}
   188  	return ListResponse{request.Accounts}, nil
   189  }
   190  
   191  // ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller
   192  func (ui *CommandlineUI) ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) {
   193  
   194  	ui.mu.Lock()
   195  	defer ui.mu.Unlock()
   196  
   197  	fmt.Printf("-------- New Account request--------------\n\n")
   198  	fmt.Printf("A request has been made to create a new account. \n")
   199  	fmt.Printf("Approving this operation means that a new account is created,\n")
   200  	fmt.Printf("and the address is returned to the external caller\n\n")
   201  	showMetadata(request.Meta)
   202  	if !ui.confirm() {
   203  		return NewAccountResponse{false}, nil
   204  	}
   205  	return NewAccountResponse{true}, nil
   206  }
   207  
   208  // ShowError displays error message to user
   209  func (ui *CommandlineUI) ShowError(message string) {
   210  	fmt.Printf("## Error \n%s\n", message)
   211  	fmt.Printf("-------------------------------------------\n")
   212  }
   213  
   214  // ShowInfo displays info message to user
   215  func (ui *CommandlineUI) ShowInfo(message string) {
   216  	fmt.Printf("## Info \n%s\n", message)
   217  }
   218  
   219  func (ui *CommandlineUI) OnApprovedTx(tx xcbapi.SignTransactionResult) {
   220  	fmt.Printf("Transaction signed:\n ")
   221  	if jsn, err := json.MarshalIndent(tx.Tx, "  ", "  "); err != nil {
   222  		fmt.Printf("WARN: marshalling error %v\n", err)
   223  	} else {
   224  		fmt.Println(string(jsn))
   225  	}
   226  }
   227  
   228  func (ui *CommandlineUI) OnSignerStartup(info StartupInfo) {
   229  
   230  	fmt.Printf("------- Signer info -------\n")
   231  	for k, v := range info.Info {
   232  		fmt.Printf("* %v : %v\n", k, v)
   233  	}
   234  }