jeth.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. // Copyright 2015 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 rpc
  17. import (
  18. "encoding/json"
  19. "fmt"
  20. "github.com/ethereum/go-ethereum/cmd/utils"
  21. "github.com/ethereum/go-ethereum/jsre"
  22. "github.com/ethereum/go-ethereum/logger"
  23. "github.com/ethereum/go-ethereum/logger/glog"
  24. "github.com/ethereum/go-ethereum/rpc/comms"
  25. "github.com/ethereum/go-ethereum/rpc/shared"
  26. "github.com/ethereum/go-ethereum/rpc/useragent"
  27. "github.com/ethereum/go-ethereum/xeth"
  28. "github.com/robertkrimen/otto"
  29. )
  30. type Jeth struct {
  31. ethApi shared.EthereumApi
  32. re *jsre.JSRE
  33. client comms.EthereumClient
  34. fe xeth.Frontend
  35. }
  36. func NewJeth(ethApi shared.EthereumApi, re *jsre.JSRE, client comms.EthereumClient, fe xeth.Frontend) *Jeth {
  37. return &Jeth{ethApi, re, client, fe}
  38. }
  39. func (self *Jeth) err(call otto.FunctionCall, code int, msg string, id interface{}) (response otto.Value) {
  40. m := shared.NewRpcErrorResponse(id, shared.JsonRpcVersion, code, fmt.Errorf(msg))
  41. errObj, _ := json.Marshal(m.Error)
  42. errRes, _ := json.Marshal(m)
  43. call.Otto.Run("ret_error = " + string(errObj))
  44. res, _ := call.Otto.Run("ret_response = " + string(errRes))
  45. return res
  46. }
  47. func (self *Jeth) Send(call otto.FunctionCall) (response otto.Value) {
  48. reqif, err := call.Argument(0).Export()
  49. if err != nil {
  50. return self.err(call, -32700, err.Error(), nil)
  51. }
  52. jsonreq, err := json.Marshal(reqif)
  53. var reqs []shared.Request
  54. batch := true
  55. err = json.Unmarshal(jsonreq, &reqs)
  56. if err != nil {
  57. reqs = make([]shared.Request, 1)
  58. err = json.Unmarshal(jsonreq, &reqs[0])
  59. batch = false
  60. }
  61. call.Otto.Set("response_len", len(reqs))
  62. call.Otto.Run("var ret_response = new Array(response_len);")
  63. for i, req := range reqs {
  64. var respif interface{}
  65. err := self.client.Send(&req)
  66. if err != nil {
  67. return self.err(call, -32603, err.Error(), req.Id)
  68. }
  69. recv:
  70. respif, err = self.client.Recv()
  71. if err != nil {
  72. return self.err(call, -32603, err.Error(), req.Id)
  73. }
  74. agentreq, isRequest := respif.(*shared.Request)
  75. if isRequest {
  76. self.handleRequest(agentreq)
  77. goto recv // receive response after agent interaction
  78. }
  79. sucres, isSuccessResponse := respif.(*shared.SuccessResponse)
  80. errres, isErrorResponse := respif.(*shared.ErrorResponse)
  81. if !isSuccessResponse && !isErrorResponse {
  82. return self.err(call, -32603, fmt.Sprintf("Invalid response type (%T)", respif), req.Id)
  83. }
  84. call.Otto.Set("ret_jsonrpc", shared.JsonRpcVersion)
  85. call.Otto.Set("ret_id", req.Id)
  86. var res []byte
  87. if isSuccessResponse {
  88. res, err = json.Marshal(sucres.Result)
  89. } else if isErrorResponse {
  90. res, err = json.Marshal(errres.Error)
  91. }
  92. call.Otto.Set("ret_result", string(res))
  93. call.Otto.Set("response_idx", i)
  94. response, err = call.Otto.Run(`
  95. ret_response[response_idx] = { jsonrpc: ret_jsonrpc, id: ret_id, result: JSON.parse(ret_result) };
  96. `)
  97. }
  98. if !batch {
  99. call.Otto.Run("ret_response = ret_response[0];")
  100. }
  101. if call.Argument(1).IsObject() {
  102. call.Otto.Set("callback", call.Argument(1))
  103. call.Otto.Run(`
  104. if (Object.prototype.toString.call(callback) == '[object Function]') {
  105. callback(null, ret_response);
  106. }
  107. `)
  108. }
  109. return
  110. }
  111. // handleRequest will handle user agent requests by interacting with the user and sending
  112. // the user response back to the geth service
  113. func (self *Jeth) handleRequest(req *shared.Request) bool {
  114. var err error
  115. var args []interface{}
  116. if err = json.Unmarshal(req.Params, &args); err != nil {
  117. glog.V(logger.Info).Infof("Unable to parse agent request - %v\n", err)
  118. return false
  119. }
  120. switch req.Method {
  121. case useragent.AskPasswordMethod:
  122. return self.askPassword(req.Id, req.Jsonrpc, args)
  123. case useragent.ConfirmTransactionMethod:
  124. return self.confirmTransaction(req.Id, req.Jsonrpc, args)
  125. }
  126. return false
  127. }
  128. // askPassword will ask the user to supply the password for a given account
  129. func (self *Jeth) askPassword(id interface{}, jsonrpc string, args []interface{}) bool {
  130. var err error
  131. var passwd string
  132. if len(args) >= 1 {
  133. if account, ok := args[0].(string); ok {
  134. fmt.Printf("Unlock account %s\n", account)
  135. passwd, err = utils.PromptPassword("Passphrase: ", true)
  136. } else {
  137. return false
  138. }
  139. }
  140. if err = self.client.Send(shared.NewRpcResponse(id, jsonrpc, passwd, err)); err != nil {
  141. glog.V(logger.Info).Infof("Unable to send user agent ask password response - %v\n", err)
  142. }
  143. return err == nil
  144. }
  145. func (self *Jeth) confirmTransaction(id interface{}, jsonrpc string, args []interface{}) bool {
  146. // Accept all tx which are send from this console
  147. return self.client.Send(shared.NewRpcResponse(id, jsonrpc, true, nil)) == nil
  148. }