cliui.go 8.1 KB

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