jeth.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU 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. // go-ethereum 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 General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. 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. // err returns an error object for the given error code and message.
  34. func (self *Jeth) err(call otto.FunctionCall, code int, msg string, id interface{}) (response otto.Value) {
  35. m := rpc.JSONErrResponse{
  36. Version: "2.0",
  37. Id: id,
  38. Error: rpc.JSONError{
  39. Code: code,
  40. Message: msg,
  41. },
  42. }
  43. errObj, _ := json.Marshal(m.Error)
  44. errRes, _ := json.Marshal(m)
  45. call.Otto.Run("ret_error = " + string(errObj))
  46. res, _ := call.Otto.Run("ret_response = " + string(errRes))
  47. return res
  48. }
  49. // UnlockAccount asks the user for the password and than executes the jeth.UnlockAccount callback in the jsre.
  50. // It will need the public address for the account to unlock as first argument.
  51. // The second argument is an optional string with the password. If not given the user is prompted for the password.
  52. // The third argument is an optional integer which specifies for how long the account will be unlocked (in seconds).
  53. func (self *Jeth) UnlockAccount(call otto.FunctionCall) (response otto.Value) {
  54. var account, passwd otto.Value
  55. duration := otto.NullValue()
  56. if !call.Argument(0).IsString() {
  57. fmt.Println("first argument must be the account to unlock")
  58. return otto.FalseValue()
  59. }
  60. account = call.Argument(0)
  61. // if password is not given or as null value -> ask user for password
  62. if call.Argument(1).IsUndefined() || call.Argument(1).IsNull() {
  63. fmt.Printf("Unlock account %s\n", account)
  64. if input, err := Stdin.PasswordPrompt("Passphrase: "); err != nil {
  65. throwJSExeception(err.Error())
  66. } else {
  67. passwd, _ = otto.ToValue(input)
  68. }
  69. } else {
  70. if !call.Argument(1).IsString() {
  71. throwJSExeception("password must be a string")
  72. }
  73. passwd = call.Argument(1)
  74. }
  75. // third argument is the duration how long the account must be unlocked.
  76. // verify that its a number.
  77. if call.Argument(2).IsDefined() && !call.Argument(2).IsNull() {
  78. if !call.Argument(2).IsNumber() {
  79. throwJSExeception("unlock duration must be a number")
  80. }
  81. duration = call.Argument(2)
  82. }
  83. // jeth.unlockAccount will send the request to the backend.
  84. if val, err := call.Otto.Call("jeth.unlockAccount", nil, account, passwd, duration); err == nil {
  85. return val
  86. } else {
  87. throwJSExeception(err.Error())
  88. }
  89. return otto.FalseValue()
  90. }
  91. // NewAccount asks the user for the password and than executes the jeth.newAccount callback in the jsre
  92. func (self *Jeth) NewAccount(call otto.FunctionCall) (response otto.Value) {
  93. var passwd string
  94. if len(call.ArgumentList) == 0 {
  95. var err error
  96. passwd, err = Stdin.PasswordPrompt("Passphrase: ")
  97. if err != nil {
  98. return otto.FalseValue()
  99. }
  100. passwd2, err := Stdin.PasswordPrompt("Repeat passphrase: ")
  101. if err != nil {
  102. return otto.FalseValue()
  103. }
  104. if passwd != passwd2 {
  105. fmt.Println("Passphrases don't match")
  106. return otto.FalseValue()
  107. }
  108. } else if len(call.ArgumentList) == 1 && call.Argument(0).IsString() {
  109. passwd, _ = call.Argument(0).ToString()
  110. } else {
  111. fmt.Println("expected 0 or 1 string argument")
  112. return otto.FalseValue()
  113. }
  114. if ret, err := call.Otto.Call("jeth.newAccount", nil, passwd); err == nil {
  115. return ret
  116. } else {
  117. fmt.Printf("%v\n", err)
  118. return otto.FalseValue()
  119. }
  120. return otto.FalseValue()
  121. }
  122. // Send will serialize the first argument, send it to the node and returns the response.
  123. func (self *Jeth) Send(call otto.FunctionCall) (response otto.Value) {
  124. // verify we got a batch request (array) or a single request (object)
  125. ro := call.Argument(0).Object()
  126. if ro == nil || (ro.Class() != "Array" && ro.Class() != "Object") {
  127. throwJSExeception("Internal Error: request must be an object or array")
  128. }
  129. // convert otto vm arguments to go values by JSON serialising and parsing.
  130. data, err := call.Otto.Call("JSON.stringify", nil, ro)
  131. if err != nil {
  132. throwJSExeception(err.Error())
  133. }
  134. jsonreq, _ := data.ToString()
  135. // parse arguments to JSON rpc requests, either to an array (batch) or to a single request.
  136. var reqs []rpc.JSONRequest
  137. batch := true
  138. if err = json.Unmarshal([]byte(jsonreq), &reqs); err != nil {
  139. // single request?
  140. reqs = make([]rpc.JSONRequest, 1)
  141. if err = json.Unmarshal([]byte(jsonreq), &reqs[0]); err != nil {
  142. throwJSExeception("invalid request")
  143. }
  144. batch = false
  145. }
  146. call.Otto.Set("response_len", len(reqs))
  147. call.Otto.Run("var ret_response = new Array(response_len);")
  148. for i, req := range reqs {
  149. if err := self.client.Send(&req); err != nil {
  150. return self.err(call, -32603, err.Error(), req.Id)
  151. }
  152. result := make(map[string]interface{})
  153. if err = self.client.Recv(&result); err != nil {
  154. return self.err(call, -32603, err.Error(), req.Id)
  155. }
  156. id, _ := result["id"]
  157. jsonver, _ := result["jsonrpc"]
  158. call.Otto.Set("ret_id", id)
  159. call.Otto.Set("ret_jsonrpc", jsonver)
  160. call.Otto.Set("response_idx", i)
  161. // call was successful
  162. if res, ok := result["result"]; ok {
  163. payload, _ := json.Marshal(res)
  164. call.Otto.Set("ret_result", string(payload))
  165. response, err = call.Otto.Run(`
  166. ret_response[response_idx] = { jsonrpc: ret_jsonrpc, id: ret_id, result: JSON.parse(ret_result) };
  167. `)
  168. continue
  169. }
  170. // request returned an error
  171. if res, ok := result["error"]; ok {
  172. payload, _ := json.Marshal(res)
  173. call.Otto.Set("ret_result", string(payload))
  174. response, err = call.Otto.Run(`
  175. ret_response[response_idx] = { jsonrpc: ret_jsonrpc, id: ret_id, error: JSON.parse(ret_result) };
  176. `)
  177. continue
  178. }
  179. return self.err(call, -32603, fmt.Sprintf("Invalid response"), new(int64))
  180. }
  181. if !batch {
  182. call.Otto.Run("ret_response = ret_response[0];")
  183. }
  184. // if a callback was given execute it.
  185. if call.Argument(1).IsObject() {
  186. call.Otto.Set("callback", call.Argument(1))
  187. call.Otto.Run(`
  188. if (Object.prototype.toString.call(callback) == '[object Function]') {
  189. callback(null, ret_response);
  190. }
  191. `)
  192. }
  193. return
  194. }
  195. // throwJSExeception panics on an otto value, the Otto VM will then throw msg as a javascript error.
  196. func throwJSExeception(msg interface{}) otto.Value {
  197. p, _ := otto.ToValue(msg)
  198. panic(p)
  199. return p
  200. }
  201. // Sleep will halt the console for arg[0] seconds.
  202. func (self *Jeth) Sleep(call otto.FunctionCall) (response otto.Value) {
  203. if len(call.ArgumentList) >= 1 {
  204. if call.Argument(0).IsNumber() {
  205. sleep, _ := call.Argument(0).ToInteger()
  206. time.Sleep(time.Duration(sleep) * time.Second)
  207. return otto.TrueValue()
  208. }
  209. }
  210. return throwJSExeception("usage: sleep(<sleep in seconds>)")
  211. }
  212. // SleepBlocks will wait for a specified number of new blocks or max for a
  213. // given of seconds. sleepBlocks(nBlocks[, maxSleep]).
  214. func (self *Jeth) SleepBlocks(call otto.FunctionCall) (response otto.Value) {
  215. nBlocks := int64(0)
  216. maxSleep := int64(9999999999999999) // indefinitely
  217. nArgs := len(call.ArgumentList)
  218. if nArgs == 0 {
  219. throwJSExeception("usage: sleepBlocks(<n blocks>[, max sleep in seconds])")
  220. }
  221. if nArgs >= 1 {
  222. if call.Argument(0).IsNumber() {
  223. nBlocks, _ = call.Argument(0).ToInteger()
  224. } else {
  225. throwJSExeception("expected number as first argument")
  226. }
  227. }
  228. if nArgs >= 2 {
  229. if call.Argument(1).IsNumber() {
  230. maxSleep, _ = call.Argument(1).ToInteger()
  231. } else {
  232. throwJSExeception("expected number as second argument")
  233. }
  234. }
  235. // go through the console, this will allow web3 to call the appropriate
  236. // callbacks if a delayed response or notification is received.
  237. currentBlockNr := func() int64 {
  238. result, err := call.Otto.Run("eth.blockNumber")
  239. if err != nil {
  240. throwJSExeception(err.Error())
  241. }
  242. blockNr, err := result.ToInteger()
  243. if err != nil {
  244. throwJSExeception(err.Error())
  245. }
  246. return blockNr
  247. }
  248. targetBlockNr := currentBlockNr() + nBlocks
  249. deadline := time.Now().Add(time.Duration(maxSleep) * time.Second)
  250. for time.Now().Before(deadline) {
  251. if currentBlockNr() >= targetBlockNr {
  252. return otto.TrueValue()
  253. }
  254. time.Sleep(time.Second)
  255. }
  256. return otto.FalseValue()
  257. }