github.com/Gessiux/neatchain@v1.3.1/utilities/console/bridge.go (about) 1 // Copyright 2016 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 17 package console 18 19 import ( 20 "encoding/json" 21 "fmt" 22 "io" 23 "strings" 24 "time" 25 26 "github.com/Gessiux/neatchain/chain/accounts/usbwallet" 27 "github.com/Gessiux/neatchain/chain/log" 28 "github.com/Gessiux/neatchain/network/rpc" 29 "github.com/robertkrimen/otto" 30 ) 31 32 // bridge is a collection of JavaScript utility methods to bride the .js runtime 33 // environment and the Go RPC connection backing the remote method calls. 34 type bridge struct { 35 client *rpc.Client // RPC client to execute Ethereum requests through 36 prompter UserPrompter // Input prompter to allow interactive user feedback 37 printer io.Writer // Output writer to serialize any display strings to 38 } 39 40 // newBridge creates a new JavaScript wrapper around an RPC client. 41 func newBridge(client *rpc.Client, prompter UserPrompter, printer io.Writer) *bridge { 42 return &bridge{ 43 client: client, 44 prompter: prompter, 45 printer: printer, 46 } 47 } 48 49 // NewAccount is a wrapper around the personal.newAccount RPC method that uses a 50 // non-echoing password prompt to acquire the passphrase and executes the original 51 // RPC method (saved in jeth.newAccount) with it to actually execute the RPC call. 52 func (b *bridge) NewAccount(call otto.FunctionCall) (response otto.Value) { 53 var ( 54 password string 55 confirm string 56 err error 57 ) 58 switch { 59 // No password was specified, prompt the user for it 60 case len(call.ArgumentList) == 0: 61 if password, err = b.prompter.PromptPassword("Passphrase: "); err != nil { 62 throwJSException(err.Error()) 63 } 64 if confirm, err = b.prompter.PromptPassword("Repeat passphrase: "); err != nil { 65 throwJSException(err.Error()) 66 } 67 if password != confirm { 68 throwJSException("passphrases don't match!") 69 } 70 71 // A single string password was specified, use that 72 case len(call.ArgumentList) == 1 && call.Argument(0).IsString(): 73 password, _ = call.Argument(0).ToString() 74 75 // Otherwise fail with some error 76 default: 77 throwJSException("expected 0 or 1 string argument") 78 } 79 // Password acquired, execute the call and return 80 ret, err := call.Otto.Call("jeth.newAccount", nil, password) 81 if err != nil { 82 throwJSException(err.Error()) 83 } 84 return ret 85 } 86 87 // OpenWallet is a wrapper around personal.openWallet which can interpret and 88 // react to certain error messages, such as the Trezor PIN matrix request. 89 func (b *bridge) OpenWallet(call otto.FunctionCall) (response otto.Value) { 90 // Make sure we have an wallet specified to open 91 if !call.Argument(0).IsString() { 92 throwJSException("first argument must be the wallet URL to open") 93 } 94 wallet := call.Argument(0) 95 96 var passwd otto.Value 97 if call.Argument(1).IsUndefined() || call.Argument(1).IsNull() { 98 passwd, _ = otto.ToValue("") 99 } else { 100 passwd = call.Argument(1) 101 } 102 // Open the wallet and return if successful in itself 103 val, err := call.Otto.Call("jeth.openWallet", nil, wallet, passwd) 104 if err == nil { 105 return val 106 } 107 // Wallet open failed, report error unless it's a PIN entry 108 if !strings.HasSuffix(err.Error(), usbwallet.ErrTrezorPINNeeded.Error()) { 109 throwJSException(err.Error()) 110 } 111 // Trezor PIN matrix input requested, display the matrix to the user and fetch the data 112 fmt.Fprintf(b.printer, "Look at the device for number positions\n\n") 113 fmt.Fprintf(b.printer, "7 | 8 | 9\n") 114 fmt.Fprintf(b.printer, "--+---+--\n") 115 fmt.Fprintf(b.printer, "4 | 5 | 6\n") 116 fmt.Fprintf(b.printer, "--+---+--\n") 117 fmt.Fprintf(b.printer, "1 | 2 | 3\n\n") 118 119 if input, err := b.prompter.PromptPassword("Please enter current PIN: "); err != nil { 120 throwJSException(err.Error()) 121 } else { 122 passwd, _ = otto.ToValue(input) 123 } 124 if val, err = call.Otto.Call("jeth.openWallet", nil, wallet, passwd); err != nil { 125 throwJSException(err.Error()) 126 } 127 return val 128 } 129 130 // UnlockAccount is a wrapper around the personal.unlockAccount RPC method that 131 // uses a non-echoing password prompt to acquire the passphrase and executes the 132 // original RPC method (saved in jeth.unlockAccount) with it to actually execute 133 // the RPC call. 134 func (b *bridge) UnlockAccount(call otto.FunctionCall) (response otto.Value) { 135 // Make sure we have an account specified to unlock 136 if !call.Argument(0).IsString() { 137 throwJSException("first argument must be the account to unlock") 138 } 139 account := call.Argument(0) 140 //account := call.Argument(0).String() 141 142 //accountByte := []byte(account) 143 //if len(accountByte) >= 2 && !(accountByte[0] == '0' && (accountByte[1] == 'x' || accountByte[1] == 'X')) { 144 // account = hexutil.Encode(accountByte) 145 //} 146 147 // If password is not given or is the null value, prompt the user for it 148 var passwd otto.Value 149 150 if call.Argument(1).IsUndefined() || call.Argument(1).IsNull() { 151 fmt.Fprintf(b.printer, "Unlock account %s\n", account) 152 if input, err := b.prompter.PromptPassword("Passphrase: "); err != nil { 153 throwJSException(err.Error()) 154 } else { 155 passwd, _ = otto.ToValue(input) 156 } 157 } else { 158 if !call.Argument(1).IsString() { 159 throwJSException("password must be a string") 160 } 161 passwd = call.Argument(1) 162 } 163 // Third argument is the duration how long the account must be unlocked. 164 duration := otto.NullValue() 165 if call.Argument(2).IsDefined() && !call.Argument(2).IsNull() { 166 if !call.Argument(2).IsNumber() { 167 throwJSException("unlock duration must be a number") 168 } 169 duration = call.Argument(2) 170 } 171 // Send the request to the backend and return 172 val, err := call.Otto.Call("jeth.unlockAccount", nil, account, passwd, duration) 173 if err != nil { 174 throwJSException(err.Error()) 175 } 176 return val 177 } 178 179 // Sign is a wrapper around the personal.sign RPC method that uses a non-echoing password 180 // prompt to acquire the passphrase and executes the original RPC method (saved in 181 // jeth.sign) with it to actually execute the RPC call. 182 func (b *bridge) Sign(call otto.FunctionCall) (response otto.Value) { 183 var ( 184 message = call.Argument(0) 185 account = call.Argument(1) 186 passwd = call.Argument(2) 187 ) 188 189 if !message.IsString() { 190 throwJSException("first argument must be the message to sign") 191 } 192 if !account.IsString() { 193 throwJSException("second argument must be the account to sign with") 194 } 195 196 // if the password is not given or null ask the user and ensure password is a string 197 if passwd.IsUndefined() || passwd.IsNull() { 198 fmt.Fprintf(b.printer, "Give password for account %s\n", account) 199 if input, err := b.prompter.PromptPassword("Passphrase: "); err != nil { 200 throwJSException(err.Error()) 201 } else { 202 passwd, _ = otto.ToValue(input) 203 } 204 } 205 if !passwd.IsString() { 206 throwJSException("third argument must be the password to unlock the account") 207 } 208 209 // Send the request to the backend and return 210 val, err := call.Otto.Call("jeth.sign", nil, message, account, passwd) 211 if err != nil { 212 throwJSException(err.Error()) 213 } 214 return val 215 } 216 217 // Sleep will block the console for the specified number of seconds. 218 func (b *bridge) Sleep(call otto.FunctionCall) (response otto.Value) { 219 if call.Argument(0).IsNumber() { 220 sleep, _ := call.Argument(0).ToInteger() 221 time.Sleep(time.Duration(sleep) * time.Second) 222 return otto.TrueValue() 223 } 224 return throwJSException("usage: sleep(<number of seconds>)") 225 } 226 227 // SleepBlocks will block the console for a specified number of new blocks optionally 228 // until the given timeout is reached. 229 func (b *bridge) SleepBlocks(call otto.FunctionCall) (response otto.Value) { 230 var ( 231 blocks = int64(0) 232 sleep = int64(9999999999999999) // indefinitely 233 ) 234 // Parse the input parameters for the sleep 235 nArgs := len(call.ArgumentList) 236 if nArgs == 0 { 237 throwJSException("usage: sleepBlocks(<n blocks>[, max sleep in seconds])") 238 } 239 if nArgs >= 1 { 240 if call.Argument(0).IsNumber() { 241 blocks, _ = call.Argument(0).ToInteger() 242 } else { 243 throwJSException("expected number as first argument") 244 } 245 } 246 if nArgs >= 2 { 247 if call.Argument(1).IsNumber() { 248 sleep, _ = call.Argument(1).ToInteger() 249 } else { 250 throwJSException("expected number as second argument") 251 } 252 } 253 // go through the console, this will allow web3 to call the appropriate 254 // callbacks if a delayed response or notification is received. 255 blockNumber := func() int64 { 256 result, err := call.Otto.Run("eth.blockNumber") 257 if err != nil { 258 throwJSException(err.Error()) 259 } 260 block, err := result.ToInteger() 261 if err != nil { 262 throwJSException(err.Error()) 263 } 264 return block 265 } 266 // Poll the current block number until either it ot a timeout is reached 267 targetBlockNr := blockNumber() + blocks 268 deadline := time.Now().Add(time.Duration(sleep) * time.Second) 269 270 for time.Now().Before(deadline) { 271 if blockNumber() >= targetBlockNr { 272 return otto.TrueValue() 273 } 274 time.Sleep(time.Second) 275 } 276 return otto.FalseValue() 277 } 278 279 type jsonrpcCall struct { 280 Id int64 281 Method string 282 Params []interface{} 283 } 284 285 // Send implements the web3 provider "send" method. 286 func (b *bridge) Send(call otto.FunctionCall) (response otto.Value) { 287 // Remarshal the request into a Go value. 288 JSON, _ := call.Otto.Object("JSON") 289 reqVal, err := JSON.Call("stringify", call.Argument(0)) 290 if err != nil { 291 throwJSException(err.Error()) 292 } 293 var ( 294 rawReq = reqVal.String() 295 dec = json.NewDecoder(strings.NewReader(rawReq)) 296 reqs []jsonrpcCall 297 batch bool 298 ) 299 dec.UseNumber() // avoid float64s 300 if rawReq[0] == '[' { 301 batch = true 302 dec.Decode(&reqs) 303 } else { 304 batch = false 305 reqs = make([]jsonrpcCall, 1) 306 dec.Decode(&reqs[0]) 307 } 308 309 // Execute the requests. 310 resps, _ := call.Otto.Object("new Array()") 311 for _, req := range reqs { 312 resp, _ := call.Otto.Object(`({"jsonrpc":"2.0"})`) 313 resp.Set("id", req.Id) 314 var result json.RawMessage 315 err = b.client.Call(&result, req.Method, req.Params...) 316 switch err := err.(type) { 317 case nil: 318 if result == nil { 319 // Special case null because it is decoded as an empty 320 // raw message for some reason. 321 resp.Set("result", otto.NullValue()) 322 } else { 323 resultVal, err := JSON.Call("parse", string(result)) 324 if err != nil { 325 setError(resp, -32603, err.Error()) 326 } else { 327 resp.Set("result", resultVal) 328 } 329 } 330 case rpc.Error: 331 setError(resp, err.ErrorCode(), err.Error()) 332 default: 333 setError(resp, -32603, err.Error()) 334 } 335 resps.Call("push", resp) 336 } 337 338 // Return the responses either to the callback (if supplied) 339 // or directly as the return value. 340 if batch { 341 response = resps.Value() 342 } else { 343 response, _ = resps.Get("0") 344 } 345 if fn := call.Argument(1); fn.Class() == "Function" { 346 fn.Call(otto.NullValue(), otto.NullValue(), response) 347 return otto.UndefinedValue() 348 } 349 return response 350 } 351 352 func setError(resp *otto.Object, code int, msg string) { 353 resp.Set("error", map[string]interface{}{"code": code, "message": msg}) 354 } 355 356 // throwJSException panics on an otto.Value. The Otto VM will recover from the 357 // Go panic and throw msg as a JavaScript error. 358 func throwJSException(msg interface{}) otto.Value { 359 val, err := otto.ToValue(msg) 360 if err != nil { 361 log.Error("Failed to serialize JavaScript exception", "exception", msg, "err", err) 362 } 363 panic(val) 364 }