jeth.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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 utils
  17. import (
  18. "encoding/json"
  19. "fmt"
  20. "time"
  21. "github.com/ethereum/go-ethereum/jsre"
  22. "github.com/ethereum/go-ethereum/rpc"
  23. "github.com/robertkrimen/otto"
  24. )
  25. type Jeth struct {
  26. re *jsre.JSRE
  27. client rpc.Client
  28. }
  29. // NewJeth create a new backend for the JSRE console
  30. func NewJeth(re *jsre.JSRE, client rpc.Client) *Jeth {
  31. return &Jeth{re, client}
  32. }
  33. func (self *Jeth) err(call otto.FunctionCall, code int, msg string, id *int64) (response otto.Value) {
  34. m := rpc.JSONErrResponse{
  35. Version: "2.0",
  36. Id: id,
  37. Error: rpc.JSONError{
  38. Code: code,
  39. Message: msg,
  40. },
  41. }
  42. errObj, _ := json.Marshal(m.Error)
  43. errRes, _ := json.Marshal(m)
  44. call.Otto.Run("ret_error = " + string(errObj))
  45. res, _ := call.Otto.Run("ret_response = " + string(errRes))
  46. return res
  47. }
  48. // UnlockAccount asks the user for the password and than executes the jeth.UnlockAccount callback in the jsre
  49. func (self *Jeth) UnlockAccount(call otto.FunctionCall) (response otto.Value) {
  50. var account, passwd string
  51. timeout := int64(300)
  52. var ok bool
  53. if len(call.ArgumentList) == 0 {
  54. fmt.Println("expected address of account to unlock")
  55. return otto.FalseValue()
  56. }
  57. if len(call.ArgumentList) >= 1 {
  58. if accountExport, err := call.Argument(0).Export(); err == nil {
  59. if account, ok = accountExport.(string); ok {
  60. if len(call.ArgumentList) == 1 {
  61. fmt.Printf("Unlock account %s\n", account)
  62. passwd, err = PromptPassword("Passphrase: ", true)
  63. if err != nil {
  64. return otto.FalseValue()
  65. }
  66. }
  67. }
  68. }
  69. }
  70. if len(call.ArgumentList) >= 2 {
  71. if passwdExport, err := call.Argument(1).Export(); err == nil {
  72. passwd, _ = passwdExport.(string)
  73. }
  74. }
  75. if len(call.ArgumentList) >= 3 {
  76. if timeoutExport, err := call.Argument(2).Export(); err == nil {
  77. timeout, _ = timeoutExport.(int64)
  78. }
  79. }
  80. if val, err := call.Otto.Call("jeth.unlockAccount", nil, account, passwd, timeout); err == nil {
  81. return val
  82. }
  83. return otto.FalseValue()
  84. }
  85. // NewAccount asks the user for the password and than executes the jeth.newAccount callback in the jsre
  86. func (self *Jeth) NewAccount(call otto.FunctionCall) (response otto.Value) {
  87. var passwd string
  88. if len(call.ArgumentList) == 0 {
  89. var err error
  90. passwd, err = PromptPassword("Passphrase: ", true)
  91. if err != nil {
  92. return otto.FalseValue()
  93. }
  94. passwd2, err := PromptPassword("Repeat passphrase: ", true)
  95. if err != nil {
  96. return otto.FalseValue()
  97. }
  98. if passwd != passwd2 {
  99. fmt.Println("Passphrases don't match")
  100. return otto.FalseValue()
  101. }
  102. } else if len(call.ArgumentList) == 1 && call.Argument(0).IsString() {
  103. passwd, _ = call.Argument(0).ToString()
  104. } else {
  105. fmt.Println("expected 0 or 1 string argument")
  106. return otto.FalseValue()
  107. }
  108. if ret, err := call.Otto.Call("jeth.newAccount", nil, passwd); err == nil {
  109. return ret
  110. } else {
  111. fmt.Printf("%v\n", err)
  112. return otto.FalseValue()
  113. }
  114. return otto.FalseValue()
  115. }
  116. func (self *Jeth) Send(call otto.FunctionCall) (response otto.Value) {
  117. reqif, err := call.Argument(0).Export()
  118. if err != nil {
  119. return self.err(call, -32700, err.Error(), nil)
  120. }
  121. jsonreq, err := json.Marshal(reqif)
  122. var reqs []rpc.JSONRequest
  123. batch := true
  124. err = json.Unmarshal(jsonreq, &reqs)
  125. if err != nil {
  126. reqs = make([]rpc.JSONRequest, 1)
  127. err = json.Unmarshal(jsonreq, &reqs[0])
  128. batch = false
  129. }
  130. call.Otto.Set("response_len", len(reqs))
  131. call.Otto.Run("var ret_response = new Array(response_len);")
  132. for i, req := range reqs {
  133. err := self.client.Send(&req)
  134. if err != nil {
  135. return self.err(call, -32603, err.Error(), req.Id)
  136. }
  137. result := make(map[string]interface{})
  138. err = self.client.Recv(&result)
  139. if err != nil {
  140. return self.err(call, -32603, err.Error(), req.Id)
  141. }
  142. _, isSuccessResponse := result["result"]
  143. _, isErrorResponse := result["error"]
  144. if !isSuccessResponse && !isErrorResponse {
  145. return self.err(call, -32603, fmt.Sprintf("Invalid response"), new(int64))
  146. }
  147. id, _ := result["id"]
  148. call.Otto.Set("ret_id", id)
  149. jsonver, _ := result["jsonrpc"]
  150. call.Otto.Set("ret_jsonrpc", jsonver)
  151. var payload []byte
  152. if isSuccessResponse {
  153. payload, _ = json.Marshal(result["result"])
  154. } else if isErrorResponse {
  155. payload, _ = json.Marshal(result["error"])
  156. }
  157. call.Otto.Set("ret_result", string(payload))
  158. call.Otto.Set("response_idx", i)
  159. response, err = call.Otto.Run(`
  160. ret_response[response_idx] = { jsonrpc: ret_jsonrpc, id: ret_id, result: JSON.parse(ret_result) };
  161. `)
  162. }
  163. if !batch {
  164. call.Otto.Run("ret_response = ret_response[0];")
  165. }
  166. if call.Argument(1).IsObject() {
  167. call.Otto.Set("callback", call.Argument(1))
  168. call.Otto.Run(`
  169. if (Object.prototype.toString.call(callback) == '[object Function]') {
  170. callback(null, ret_response);
  171. }
  172. `)
  173. }
  174. return
  175. }
  176. /*
  177. // handleRequest will handle user agent requests by interacting with the user and sending
  178. // the user response back to the geth service
  179. func (self *Jeth) handleRequest(req *shared.Request) bool {
  180. var err error
  181. var args []interface{}
  182. if err = json.Unmarshal(req.Params, &args); err != nil {
  183. glog.V(logger.Info).Infof("Unable to parse agent request - %v\n", err)
  184. return false
  185. }
  186. switch req.Method {
  187. case useragent.AskPasswordMethod:
  188. return self.askPassword(req.Id, req.Jsonrpc, args)
  189. case useragent.ConfirmTransactionMethod:
  190. return self.confirmTransaction(req.Id, req.Jsonrpc, args)
  191. }
  192. return false
  193. }
  194. // askPassword will ask the user to supply the password for a given account
  195. func (self *Jeth) askPassword(id interface{}, jsonrpc string, args []interface{}) bool {
  196. var err error
  197. var passwd string
  198. if len(args) >= 1 {
  199. if account, ok := args[0].(string); ok {
  200. fmt.Printf("Unlock account %s\n", account)
  201. } else {
  202. return false
  203. }
  204. }
  205. passwd, err = PromptPassword("Passphrase: ", true)
  206. if err = self.client.Send(shared.NewRpcResponse(id, jsonrpc, passwd, err)); err != nil {
  207. glog.V(logger.Info).Infof("Unable to send user agent ask password response - %v\n", err)
  208. }
  209. return err == nil
  210. }
  211. func (self *Jeth) confirmTransaction(id interface{}, jsonrpc string, args []interface{}) bool {
  212. // Accept all tx which are send from this console
  213. return self.client.Send(shared.NewRpcResponse(id, jsonrpc, true, nil)) == nil
  214. }
  215. */
  216. // throwJSExeception panics on an otto value, the Otto VM will then throw msg as a javascript error.
  217. func throwJSExeception(msg interface{}) otto.Value {
  218. p, _ := otto.ToValue(msg)
  219. panic(p)
  220. return p
  221. }
  222. // Sleep will halt the console for arg[0] seconds.
  223. func (self *Jeth) Sleep(call otto.FunctionCall) (response otto.Value) {
  224. if len(call.ArgumentList) >= 1 {
  225. if call.Argument(0).IsNumber() {
  226. sleep, _ := call.Argument(0).ToInteger()
  227. time.Sleep(time.Duration(sleep) * time.Second)
  228. return otto.TrueValue()
  229. }
  230. }
  231. return throwJSExeception("usage: sleep(<sleep in seconds>)")
  232. }
  233. // SleepBlocks will wait for a specified number of new blocks or max for a
  234. // given of seconds. sleepBlocks(nBlocks[, maxSleep]).
  235. func (self *Jeth) SleepBlocks(call otto.FunctionCall) (response otto.Value) {
  236. nBlocks := int64(0)
  237. maxSleep := int64(9999999999999999) // indefinitely
  238. nArgs := len(call.ArgumentList)
  239. if nArgs == 0 {
  240. throwJSExeception("usage: sleepBlocks(<n blocks>[, max sleep in seconds])")
  241. }
  242. if nArgs >= 1 {
  243. if call.Argument(0).IsNumber() {
  244. nBlocks, _ = call.Argument(0).ToInteger()
  245. } else {
  246. throwJSExeception("expected number as first argument")
  247. }
  248. }
  249. if nArgs >= 2 {
  250. if call.Argument(1).IsNumber() {
  251. maxSleep, _ = call.Argument(1).ToInteger()
  252. } else {
  253. throwJSExeception("expected number as second argument")
  254. }
  255. }
  256. // go through the console, this will allow web3 to call the appropriate
  257. // callbacks if a delayed response or notification is received.
  258. currentBlockNr := func() int64 {
  259. result, err := call.Otto.Run("eth.blockNumber")
  260. if err != nil {
  261. throwJSExeception(err.Error())
  262. }
  263. blockNr, err := result.ToInteger()
  264. if err != nil {
  265. throwJSExeception(err.Error())
  266. }
  267. return blockNr
  268. }
  269. targetBlockNr := currentBlockNr() + nBlocks
  270. deadline := time.Now().Add(time.Duration(maxSleep) * time.Second)
  271. for time.Now().Before(deadline) {
  272. if currentBlockNr() >= targetBlockNr {
  273. return otto.TrueValue()
  274. }
  275. time.Sleep(time.Second)
  276. }
  277. return otto.FalseValue()
  278. }