cliui.go 7.3 KB

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