@@ -37,7 +37,8 @@ func NewJeth(re *jsre.JSRE, client rpc.Client) *Jeth {
3737 return & Jeth {re , client }
3838}
3939
40- func (self * Jeth ) err (call otto.FunctionCall , code int , msg string , id * int64 ) (response otto.Value ) {
40+ // err returns an error object for the given error code and message.
41+ func (self * Jeth ) err (call otto.FunctionCall , code int , msg string , id interface {}) (response otto.Value ) {
4142 m := rpc.JSONErrResponse {
4243 Version : "2.0" ,
4344 Id : id ,
@@ -56,44 +57,50 @@ func (self *Jeth) err(call otto.FunctionCall, code int, msg string, id *int64) (
5657 return res
5758}
5859
59- // UnlockAccount asks the user for the password and than executes the jeth.UnlockAccount callback in the jsre
60+ // UnlockAccount asks the user for the password and than executes the jeth.UnlockAccount callback in the jsre.
61+ // It will need the public address for the account to unlock as first argument.
62+ // The second argument is an optional string with the password. If not given the user is prompted for the password.
63+ // The third argument is an optional integer which specifies for how long the account will be unlocked (in seconds).
6064func (self * Jeth ) UnlockAccount (call otto.FunctionCall ) (response otto.Value ) {
61- var account , passwd string
62- timeout := int64 (300 )
63- var ok bool
65+ var account , passwd otto.Value
66+ duration := otto .NullValue ()
6467
65- if len ( call .ArgumentList ) == 0 {
66- fmt .Println ("expected address of account to unlock" )
68+ if ! call .Argument ( 0 ). IsString () {
69+ fmt .Println ("first argument must be the account to unlock" )
6770 return otto .FalseValue ()
6871 }
6972
70- if len (call .ArgumentList ) >= 1 {
71- if accountExport , err := call .Argument (0 ).Export (); err == nil {
72- if account , ok = accountExport .(string ); ok {
73- if len (call .ArgumentList ) == 1 {
74- fmt .Printf ("Unlock account %s\n " , account )
75- passwd , err = PromptPassword ("Passphrase: " , true )
76- if err != nil {
77- return otto .FalseValue ()
78- }
79- }
80- }
73+ account = call .Argument (0 )
74+
75+ // if password is not given or as null value -> ask user for password
76+ if call .Argument (1 ).IsUndefined () || call .Argument (1 ).IsNull () {
77+ fmt .Printf ("Unlock account %s\n " , account )
78+ if password , err := PromptPassword ("Passphrase: " , true ); err == nil {
79+ passwd , _ = otto .ToValue (password )
80+ } else {
81+ throwJSExeception (err .Error ())
8182 }
82- }
83- if len (call .ArgumentList ) >= 2 {
84- if passwdExport , err := call .Argument (1 ).Export (); err == nil {
85- passwd , _ = passwdExport .(string )
83+ } else {
84+ if ! call .Argument (1 ).IsString () {
85+ throwJSExeception ("password must be a string" )
8686 }
87+ passwd = call .Argument (1 )
8788 }
8889
89- if len (call .ArgumentList ) >= 3 {
90- if timeoutExport , err := call .Argument (2 ).Export (); err == nil {
91- timeout , _ = timeoutExport .(int64 )
90+ // third argument is the duration how long the account must be unlocked.
91+ // verify that its a number.
92+ if call .Argument (2 ).IsDefined () && ! call .Argument (2 ).IsNull () {
93+ if ! call .Argument (2 ).IsNumber () {
94+ throwJSExeception ("unlock duration must be a number" )
9295 }
96+ duration = call .Argument (2 )
9397 }
9498
95- if val , err := call .Otto .Call ("jeth.unlockAccount" , nil , account , passwd , timeout ); err == nil {
99+ // jeth.unlockAccount will send the request to the backend.
100+ if val , err := call .Otto .Call ("jeth.unlockAccount" , nil , account , passwd , duration ); err == nil {
96101 return val
102+ } else {
103+ throwJSExeception (err .Error ())
97104 }
98105
99106 return otto .FalseValue ()
@@ -134,67 +141,82 @@ func (self *Jeth) NewAccount(call otto.FunctionCall) (response otto.Value) {
134141 return otto .FalseValue ()
135142}
136143
144+ // Send will serialize the first argument, send it to the node and returns the response.
137145func (self * Jeth ) Send (call otto.FunctionCall ) (response otto.Value ) {
138- reqif , err := call .Argument (0 ).Export ()
146+ // verify we got a batch request (array) or a single request (object)
147+ ro := call .Argument (0 ).Object ()
148+ if ro == nil || (ro .Class () != "Array" && ro .Class () != "Object" ) {
149+ throwJSExeception ("Internal Error: request must be an object or array" )
150+ }
151+
152+ // convert otto vm arguments to go values by JSON serialising and parsing.
153+ data , err := call .Otto .Call ("JSON.stringify" , nil , ro )
139154 if err != nil {
140- return self . err ( call , - 32700 , err .Error (), nil )
155+ throwJSExeception ( err .Error ())
141156 }
142157
143- jsonreq , err := json .Marshal (reqif )
158+ jsonreq , _ := data .ToString ()
159+
160+ // parse arguments to JSON rpc requests, either to an array (batch) or to a single request.
144161 var reqs []rpc.JSONRequest
145162 batch := true
146- err = json .Unmarshal (jsonreq , & reqs )
147- if err != nil {
163+ if err = json .Unmarshal ([] byte ( jsonreq ) , & reqs ); err != nil {
164+ // single request?
148165 reqs = make ([]rpc.JSONRequest , 1 )
149- err = json .Unmarshal (jsonreq , & reqs [0 ])
166+ if err = json .Unmarshal ([]byte (jsonreq ), & reqs [0 ]); err != nil {
167+ throwJSExeception ("invalid request" )
168+ }
150169 batch = false
151170 }
152171
153172 call .Otto .Set ("response_len" , len (reqs ))
154173 call .Otto .Run ("var ret_response = new Array(response_len);" )
155174
156175 for i , req := range reqs {
157- err := self .client .Send (& req )
158- if err != nil {
176+ if err := self .client .Send (& req ); err != nil {
159177 return self .err (call , - 32603 , err .Error (), req .Id )
160178 }
161179
162180 result := make (map [string ]interface {})
163- err = self .client .Recv (& result )
164- if err != nil {
181+ if err = self .client .Recv (& result ); err != nil {
165182 return self .err (call , - 32603 , err .Error (), req .Id )
166183 }
167184
168- _ , isSuccessResponse := result ["result" ]
169- _ , isErrorResponse := result ["error" ]
170- if ! isSuccessResponse && ! isErrorResponse {
171- return self .err (call , - 32603 , fmt .Sprintf ("Invalid response" ), new (int64 ))
172- }
173-
174185 id , _ := result ["id" ]
175- call .Otto .Set ("ret_id" , id )
176-
177186 jsonver , _ := result ["jsonrpc" ]
187+
188+ call .Otto .Set ("ret_id" , id )
178189 call .Otto .Set ("ret_jsonrpc" , jsonver )
190+ call .Otto .Set ("response_idx" , i )
179191
180- var payload []byte
181- if isSuccessResponse {
182- payload , _ = json .Marshal (result ["result" ])
183- } else if isErrorResponse {
184- payload , _ = json .Marshal (result ["error" ])
192+ // call was successful
193+ if res , ok := result ["result" ]; ok {
194+ payload , _ := json .Marshal (res )
195+ call .Otto .Set ("ret_result" , string (payload ))
196+ response , err = call .Otto .Run (`
197+ ret_response[response_idx] = { jsonrpc: ret_jsonrpc, id: ret_id, result: JSON.parse(ret_result) };
198+ ` )
199+ continue
185200 }
186- call .Otto .Set ("ret_result" , string (payload ))
187- call .Otto .Set ("response_idx" , i )
188201
189- response , err = call .Otto .Run (`
190- ret_response[response_idx] = { jsonrpc: ret_jsonrpc, id: ret_id, result: JSON.parse(ret_result) };
191- ` )
202+ // request returned an error
203+ if res , ok := result ["error" ]; ok {
204+ payload , _ := json .Marshal (res )
205+ call .Otto .Set ("ret_result" , string (payload ))
206+ response , err = call .Otto .Run (`
207+ ret_response[response_idx] = { jsonrpc: ret_jsonrpc, id: ret_id, error: JSON.parse(ret_result) };
208+ ` )
209+ continue
210+ }
211+
212+ return self .err (call , - 32603 , fmt .Sprintf ("Invalid response" ), new (int64 ))
192213 }
193214
194215 if ! batch {
195216 call .Otto .Run ("ret_response = ret_response[0];" )
196217 }
197218
219+ // if a callback was given execute it.
198220 if call .Argument (1 ).IsObject () {
199221 call .Otto .Set ("callback" , call .Argument (1 ))
200222 call .Otto .Run (`
@@ -207,53 +229,6 @@ func (self *Jeth) Send(call otto.FunctionCall) (response otto.Value) {
207229 return
208230}
209231
210- /*
211- // handleRequest will handle user agent requests by interacting with the user and sending
212- // the user response back to the geth service
213- func (self *Jeth) handleRequest(req *shared.Request) bool {
214- var err error
215- var args []interface{}
216- if err = json.Unmarshal(req.Params, &args); err != nil {
217- glog.V(logger.Info).Infof("Unable to parse agent request - %v\n", err)
218- return false
219- }
220-
221- switch req.Method {
222- case useragent.AskPasswordMethod:
223- return self.askPassword(req.Id, req.Jsonrpc, args)
224- case useragent.ConfirmTransactionMethod:
225- return self.confirmTransaction(req.Id, req.Jsonrpc, args)
226- }
227-
228- return false
229- }
230-
231- // askPassword will ask the user to supply the password for a given account
232- func (self *Jeth) askPassword(id interface{}, jsonrpc string, args []interface{}) bool {
233- var err error
234- var passwd string
235- if len(args) >= 1 {
236- if account, ok := args[0].(string); ok {
237- fmt.Printf("Unlock account %s\n", account)
238- } else {
239- return false
240- }
241- }
242- passwd, err = PromptPassword("Passphrase: ", true)
243-
244- if err = self.client.Send(shared.NewRpcResponse(id, jsonrpc, passwd, err)); err != nil {
245- glog.V(logger.Info).Infof("Unable to send user agent ask password response - %v\n", err)
246- }
247-
248- return err == nil
249- }
250-
251- func (self *Jeth) confirmTransaction(id interface{}, jsonrpc string, args []interface{}) bool {
252- // Accept all tx which are send from this console
253- return self.client.Send(shared.NewRpcResponse(id, jsonrpc, true, nil)) == nil
254- }
255- */
256-
257232// throwJSExeception panics on an otto value, the Otto VM will then throw msg as a javascript error.
258233func throwJSExeception (msg interface {}) otto.Value {
259234 p , _ := otto .ToValue (msg )
0 commit comments