cliui.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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 chainId := request.Transaction.ChainID; chainId != nil {
  109. fmt.Printf("chainid: %v\n", chainId)
  110. }
  111. if list := request.Transaction.AccessList; list != nil {
  112. fmt.Printf("Accesslist\n")
  113. for i, el := range *list {
  114. fmt.Printf(" %d. %v\n", i, el.Address)
  115. for j, slot := range el.StorageKeys {
  116. fmt.Printf(" %d. %v\n", j, slot)
  117. }
  118. }
  119. }
  120. if request.Transaction.Data != nil {
  121. d := *request.Transaction.Data
  122. if len(d) > 0 {
  123. fmt.Printf("data: %v\n", hexutil.Encode(d))
  124. }
  125. }
  126. if request.Callinfo != nil {
  127. fmt.Printf("\nTransaction validation:\n")
  128. for _, m := range request.Callinfo {
  129. fmt.Printf(" * %s : %s\n", m.Typ, m.Message)
  130. }
  131. fmt.Println()
  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. // ApproveSignData prompt the user for confirmation to request to sign data
  142. func (ui *CommandlineUI) ApproveSignData(request *SignDataRequest) (SignDataResponse, error) {
  143. ui.mu.Lock()
  144. defer ui.mu.Unlock()
  145. fmt.Printf("-------- Sign data request--------------\n")
  146. fmt.Printf("Account: %s\n", request.Address.String())
  147. if len(request.Callinfo) != 0 {
  148. fmt.Printf("\nValidation messages:\n")
  149. for _, m := range request.Callinfo {
  150. fmt.Printf(" * %s : %s\n", m.Typ, m.Message)
  151. }
  152. fmt.Println()
  153. }
  154. fmt.Printf("messages:\n")
  155. for _, nvt := range request.Messages {
  156. fmt.Printf("\u00a0\u00a0%v\n", strings.TrimSpace(nvt.Pprint(1)))
  157. }
  158. fmt.Printf("raw data: \n\t%q\n", request.Rawdata)
  159. fmt.Printf("data hash: %v\n", request.Hash)
  160. fmt.Printf("-------------------------------------------\n")
  161. showMetadata(request.Meta)
  162. if !ui.confirm() {
  163. return SignDataResponse{false}, nil
  164. }
  165. return SignDataResponse{true}, nil
  166. }
  167. // ApproveListing prompt the user for confirmation to list accounts
  168. // the list of accounts to list can be modified by the UI
  169. func (ui *CommandlineUI) ApproveListing(request *ListRequest) (ListResponse, error) {
  170. ui.mu.Lock()
  171. defer ui.mu.Unlock()
  172. fmt.Printf("-------- List Account request--------------\n")
  173. fmt.Printf("A request has been made to list all accounts. \n")
  174. fmt.Printf("You can select which accounts the caller can see\n")
  175. for _, account := range request.Accounts {
  176. fmt.Printf(" [x] %v\n", account.Address.Hex())
  177. fmt.Printf(" URL: %v\n", account.URL)
  178. }
  179. fmt.Printf("-------------------------------------------\n")
  180. showMetadata(request.Meta)
  181. if !ui.confirm() {
  182. return ListResponse{nil}, nil
  183. }
  184. return ListResponse{request.Accounts}, nil
  185. }
  186. // ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller
  187. func (ui *CommandlineUI) ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) {
  188. ui.mu.Lock()
  189. defer ui.mu.Unlock()
  190. fmt.Printf("-------- New Account request--------------\n\n")
  191. fmt.Printf("A request has been made to create a new account. \n")
  192. fmt.Printf("Approving this operation means that a new account is created,\n")
  193. fmt.Printf("and the address is returned to the external caller\n\n")
  194. showMetadata(request.Meta)
  195. if !ui.confirm() {
  196. return NewAccountResponse{false}, nil
  197. }
  198. return NewAccountResponse{true}, nil
  199. }
  200. // ShowError displays error message to user
  201. func (ui *CommandlineUI) ShowError(message string) {
  202. fmt.Printf("## Error \n%s\n", message)
  203. fmt.Printf("-------------------------------------------\n")
  204. }
  205. // ShowInfo displays info message to user
  206. func (ui *CommandlineUI) ShowInfo(message string) {
  207. fmt.Printf("## Info \n%s\n", message)
  208. }
  209. func (ui *CommandlineUI) OnApprovedTx(tx ethapi.SignTransactionResult) {
  210. fmt.Printf("Transaction signed:\n ")
  211. if jsn, err := json.MarshalIndent(tx.Tx, " ", " "); err != nil {
  212. fmt.Printf("WARN: marshalling error %v\n", err)
  213. } else {
  214. fmt.Println(string(jsn))
  215. }
  216. }
  217. func (ui *CommandlineUI) OnSignerStartup(info StartupInfo) {
  218. fmt.Printf("------- Signer info -------\n")
  219. for k, v := range info.Info {
  220. fmt.Printf("* %v : %v\n", k, v)
  221. }
  222. }