cliui.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. package core
  17. import (
  18. "bufio"
  19. "encoding/json"
  20. "fmt"
  21. "os"
  22. "strings"
  23. "sync"
  24. "github.com/ethereum/go-ethereum/common/hexutil"
  25. "github.com/ethereum/go-ethereum/console/prompt"
  26. "github.com/ethereum/go-ethereum/internal/ethapi"
  27. "github.com/ethereum/go-ethereum/log"
  28. )
  29. type CommandlineUI struct {
  30. in *bufio.Reader
  31. mu sync.Mutex
  32. }
  33. func NewCommandlineUI() *CommandlineUI {
  34. return &CommandlineUI{in: bufio.NewReader(os.Stdin)}
  35. }
  36. func (ui *CommandlineUI) RegisterUIServer(api *UIServerAPI) {
  37. // noop
  38. }
  39. // readString reads a single line from stdin, trimming if from spaces, enforcing
  40. // non-emptyness.
  41. func (ui *CommandlineUI) readString() string {
  42. for {
  43. fmt.Printf("> ")
  44. text, err := ui.in.ReadString('\n')
  45. if err != nil {
  46. log.Crit("Failed to read user input", "err", err)
  47. }
  48. if text = strings.TrimSpace(text); text != "" {
  49. return text
  50. }
  51. }
  52. }
  53. func (ui *CommandlineUI) OnInputRequired(info UserInputRequest) (UserInputResponse, error) {
  54. fmt.Printf("## %s\n\n%s\n", info.Title, info.Prompt)
  55. defer fmt.Println("-----------------------")
  56. if info.IsPassword {
  57. text, err := prompt.Stdin.PromptPassword("> ")
  58. if err != nil {
  59. log.Error("Failed to read password", "error", err)
  60. return UserInputResponse{}, err
  61. }
  62. return UserInputResponse{text}, nil
  63. }
  64. text := ui.readString()
  65. return UserInputResponse{text}, nil
  66. }
  67. // confirm returns true if user enters 'Yes', otherwise false
  68. func (ui *CommandlineUI) confirm() bool {
  69. fmt.Printf("Approve? [y/N]:\n")
  70. if ui.readString() == "y" {
  71. return true
  72. }
  73. fmt.Println("-----------------------")
  74. return false
  75. }
  76. // sanitize quotes and truncates 'txt' if longer than 'limit'. If truncated,
  77. // and ellipsis is added after the quoted string
  78. func sanitize(txt string, limit int) string {
  79. if len(txt) > limit {
  80. return fmt.Sprintf("%q...", txt[:limit])
  81. }
  82. return fmt.Sprintf("%q", txt)
  83. }
  84. func showMetadata(metadata Metadata) {
  85. fmt.Printf("Request context:\n\t%v -> %v -> %v\n", metadata.Remote, metadata.Scheme, metadata.Local)
  86. fmt.Printf("\nAdditional HTTP header data, provided by the external caller:\n")
  87. fmt.Printf("\tUser-Agent: %v\n\tOrigin: %v\n", sanitize(metadata.UserAgent, 200), sanitize(metadata.Origin, 100))
  88. }
  89. // ApproveTx prompt the user for confirmation to request to sign Transaction
  90. func (ui *CommandlineUI) ApproveTx(request *SignTxRequest) (SignTxResponse, error) {
  91. ui.mu.Lock()
  92. defer ui.mu.Unlock()
  93. weival := request.Transaction.Value.ToInt()
  94. fmt.Printf("--------- Transaction request-------------\n")
  95. if to := request.Transaction.To; to != nil {
  96. fmt.Printf("to: %v\n", to.Original())
  97. if !to.ValidChecksum() {
  98. fmt.Printf("\nWARNING: Invalid checksum on to-address!\n\n")
  99. }
  100. } else {
  101. fmt.Printf("to: <contact creation>\n")
  102. }
  103. fmt.Printf("from: %v\n", request.Transaction.From.String())
  104. fmt.Printf("value: %v wei\n", weival)
  105. fmt.Printf("gas: %v (%v)\n", request.Transaction.Gas, uint64(request.Transaction.Gas))
  106. fmt.Printf("gasprice: %v wei\n", request.Transaction.GasPrice.ToInt())
  107. fmt.Printf("nonce: %v (%v)\n", request.Transaction.Nonce, uint64(request.Transaction.Nonce))
  108. if request.Transaction.Data != nil {
  109. d := *request.Transaction.Data
  110. if len(d) > 0 {
  111. fmt.Printf("data: %v\n", hexutil.Encode(d))
  112. }
  113. }
  114. if request.Callinfo != nil {
  115. fmt.Printf("\nTransaction validation:\n")
  116. for _, m := range request.Callinfo {
  117. fmt.Printf(" * %s : %s\n", m.Typ, m.Message)
  118. }
  119. fmt.Println()
  120. }
  121. fmt.Printf("\n")
  122. showMetadata(request.Meta)
  123. fmt.Printf("-------------------------------------------\n")
  124. if !ui.confirm() {
  125. return SignTxResponse{request.Transaction, false}, nil
  126. }
  127. return SignTxResponse{request.Transaction, true}, nil
  128. }
  129. // ApproveSignData prompt the user for confirmation to request to sign data
  130. func (ui *CommandlineUI) ApproveSignData(request *SignDataRequest) (SignDataResponse, error) {
  131. ui.mu.Lock()
  132. defer ui.mu.Unlock()
  133. fmt.Printf("-------- Sign data request--------------\n")
  134. fmt.Printf("Account: %s\n", request.Address.String())
  135. fmt.Printf("messages:\n")
  136. for _, nvt := range request.Messages {
  137. fmt.Printf("\u00a0\u00a0%v\n", strings.TrimSpace(nvt.Pprint(1)))
  138. }
  139. fmt.Printf("raw data: \n\t%q\n", request.Rawdata)
  140. fmt.Printf("data hash: %v\n", request.Hash)
  141. fmt.Printf("-------------------------------------------\n")
  142. showMetadata(request.Meta)
  143. if !ui.confirm() {
  144. return SignDataResponse{false}, nil
  145. }
  146. return SignDataResponse{true}, nil
  147. }
  148. // ApproveListing prompt the user for confirmation to list accounts
  149. // the list of accounts to list can be modified by the UI
  150. func (ui *CommandlineUI) ApproveListing(request *ListRequest) (ListResponse, error) {
  151. ui.mu.Lock()
  152. defer ui.mu.Unlock()
  153. fmt.Printf("-------- List Account request--------------\n")
  154. fmt.Printf("A request has been made to list all accounts. \n")
  155. fmt.Printf("You can select which accounts the caller can see\n")
  156. for _, account := range request.Accounts {
  157. fmt.Printf(" [x] %v\n", account.Address.Hex())
  158. fmt.Printf(" URL: %v\n", account.URL)
  159. }
  160. fmt.Printf("-------------------------------------------\n")
  161. showMetadata(request.Meta)
  162. if !ui.confirm() {
  163. return ListResponse{nil}, nil
  164. }
  165. return ListResponse{request.Accounts}, nil
  166. }
  167. // ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller
  168. func (ui *CommandlineUI) ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) {
  169. ui.mu.Lock()
  170. defer ui.mu.Unlock()
  171. fmt.Printf("-------- New Account request--------------\n\n")
  172. fmt.Printf("A request has been made to create a new account. \n")
  173. fmt.Printf("Approving this operation means that a new account is created,\n")
  174. fmt.Printf("and the address is returned to the external caller\n\n")
  175. showMetadata(request.Meta)
  176. if !ui.confirm() {
  177. return NewAccountResponse{false}, nil
  178. }
  179. return NewAccountResponse{true}, nil
  180. }
  181. // ShowError displays error message to user
  182. func (ui *CommandlineUI) ShowError(message string) {
  183. fmt.Printf("## Error \n%s\n", message)
  184. fmt.Printf("-------------------------------------------\n")
  185. }
  186. // ShowInfo displays info message to user
  187. func (ui *CommandlineUI) ShowInfo(message string) {
  188. fmt.Printf("## Info \n%s\n", message)
  189. }
  190. func (ui *CommandlineUI) OnApprovedTx(tx ethapi.SignTransactionResult) {
  191. fmt.Printf("Transaction signed:\n ")
  192. if jsn, err := json.MarshalIndent(tx.Tx, " ", " "); err != nil {
  193. fmt.Printf("WARN: marshalling error %v\n", err)
  194. } else {
  195. fmt.Println(string(jsn))
  196. }
  197. }
  198. func (ui *CommandlineUI) OnSignerStartup(info StartupInfo) {
  199. fmt.Printf("------- Signer info -------\n")
  200. for k, v := range info.Info {
  201. fmt.Printf("* %v : %v\n", k, v)
  202. }
  203. }