github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/console/bridge.go (about)

     1  // Copyright 2016 The Spectrum Authors
     2  // This file is part of the Spectrum library.
     3  //
     4  // The Spectrum 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 Spectrum 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 Spectrum 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/SmartMeshFoundation/Spectrum/accounts/usbwallet"
    27  	"github.com/SmartMeshFoundation/Spectrum/log"
    28  	"github.com/SmartMeshFoundation/Spectrum/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  
   141  	// If password is not given or is the null value, prompt the user for it
   142  	var passwd otto.Value
   143  
   144  	if call.Argument(1).IsUndefined() || call.Argument(1).IsNull() {
   145  		fmt.Fprintf(b.printer, "Unlock account %s\n", account)
   146  		if input, err := b.prompter.PromptPassword("Passphrase: "); err != nil {
   147  			throwJSException(err.Error())
   148  		} else {
   149  			passwd, _ = otto.ToValue(input)
   150  		}
   151  	} else {
   152  		if !call.Argument(1).IsString() {
   153  			throwJSException("password must be a string")
   154  		}
   155  		passwd = call.Argument(1)
   156  	}
   157  	// Third argument is the duration how long the account must be unlocked.
   158  	duration := otto.NullValue()
   159  	if call.Argument(2).IsDefined() && !call.Argument(2).IsNull() {
   160  		if !call.Argument(2).IsNumber() {
   161  			throwJSException("unlock duration must be a number")
   162  		}
   163  		duration = call.Argument(2)
   164  	}
   165  	// Send the request to the backend and return
   166  	val, err := call.Otto.Call("jeth.unlockAccount", nil, account, passwd, duration)
   167  	if err != nil {
   168  		throwJSException(err.Error())
   169  	}
   170  	return val
   171  }
   172  
   173  // Sign is a wrapper around the personal.sign RPC method that uses a non-echoing password
   174  // prompt to acquire the passphrase and executes the original RPC method (saved in
   175  // jeth.sign) with it to actually execute the RPC call.
   176  func (b *bridge) Sign(call otto.FunctionCall) (response otto.Value) {
   177  	var (
   178  		message = call.Argument(0)
   179  		account = call.Argument(1)
   180  		passwd  = call.Argument(2)
   181  	)
   182  
   183  	if !message.IsString() {
   184  		throwJSException("first argument must be the message to sign")
   185  	}
   186  	if !account.IsString() {
   187  		throwJSException("second argument must be the account to sign with")
   188  	}
   189  
   190  	// if the password is not given or null ask the user and ensure password is a string
   191  	if passwd.IsUndefined() || passwd.IsNull() {
   192  		fmt.Fprintf(b.printer, "Give password for account %s\n", account)
   193  		if input, err := b.prompter.PromptPassword("Passphrase: "); err != nil {
   194  			throwJSException(err.Error())
   195  		} else {
   196  			passwd, _ = otto.ToValue(input)
   197  		}
   198  	}
   199  	if !passwd.IsString() {
   200  		throwJSException("third argument must be the password to unlock the account")
   201  	}
   202  
   203  	// Send the request to the backend and return
   204  	val, err := call.Otto.Call("jeth.sign", nil, message, account, passwd)
   205  	if err != nil {
   206  		throwJSException(err.Error())
   207  	}
   208  	return val
   209  }
   210  
   211  // Sleep will block the console for the specified number of seconds.
   212  func (b *bridge) Sleep(call otto.FunctionCall) (response otto.Value) {
   213  	if call.Argument(0).IsNumber() {
   214  		sleep, _ := call.Argument(0).ToInteger()
   215  		time.Sleep(time.Duration(sleep) * time.Second)
   216  		return otto.TrueValue()
   217  	}
   218  	return throwJSException("usage: sleep(<number of seconds>)")
   219  }
   220  
   221  // SleepBlocks will block the console for a specified number of new blocks optionally
   222  // until the given timeout is reached.
   223  func (b *bridge) SleepBlocks(call otto.FunctionCall) (response otto.Value) {
   224  	var (
   225  		blocks = int64(0)
   226  		sleep  = int64(9999999999999999) // indefinitely
   227  	)
   228  	// Parse the input parameters for the sleep
   229  	nArgs := len(call.ArgumentList)
   230  	if nArgs == 0 {
   231  		throwJSException("usage: sleepBlocks(<n blocks>[, max sleep in seconds])")
   232  	}
   233  	if nArgs >= 1 {
   234  		if call.Argument(0).IsNumber() {
   235  			blocks, _ = call.Argument(0).ToInteger()
   236  		} else {
   237  			throwJSException("expected number as first argument")
   238  		}
   239  	}
   240  	if nArgs >= 2 {
   241  		if call.Argument(1).IsNumber() {
   242  			sleep, _ = call.Argument(1).ToInteger()
   243  		} else {
   244  			throwJSException("expected number as second argument")
   245  		}
   246  	}
   247  	// go through the console, this will allow web3 to call the appropriate
   248  	// callbacks if a delayed response or notification is received.
   249  	blockNumber := func() int64 {
   250  		result, err := call.Otto.Run("eth.blockNumber")
   251  		if err != nil {
   252  			throwJSException(err.Error())
   253  		}
   254  		block, err := result.ToInteger()
   255  		if err != nil {
   256  			throwJSException(err.Error())
   257  		}
   258  		return block
   259  	}
   260  	// Poll the current block number until either it ot a timeout is reached
   261  	targetBlockNr := blockNumber() + blocks
   262  	deadline := time.Now().Add(time.Duration(sleep) * time.Second)
   263  
   264  	for time.Now().Before(deadline) {
   265  		if blockNumber() >= targetBlockNr {
   266  			return otto.TrueValue()
   267  		}
   268  		time.Sleep(time.Second)
   269  	}
   270  	return otto.FalseValue()
   271  }
   272  
   273  type jsonrpcCall struct {
   274  	Id     int64
   275  	Method string
   276  	Params []interface{}
   277  }
   278  
   279  // Send implements the web3 provider "send" method.
   280  func (b *bridge) Send(call otto.FunctionCall) (response otto.Value) {
   281  	// Remarshal the request into a Go value.
   282  	JSON, _ := call.Otto.Object("JSON")
   283  	reqVal, err := JSON.Call("stringify", call.Argument(0))
   284  	if err != nil {
   285  		throwJSException(err.Error())
   286  	}
   287  	var (
   288  		rawReq = reqVal.String()
   289  		dec    = json.NewDecoder(strings.NewReader(rawReq))
   290  		reqs   []jsonrpcCall
   291  		batch  bool
   292  	)
   293  	dec.UseNumber() // avoid float64s
   294  	if rawReq[0] == '[' {
   295  		batch = true
   296  		dec.Decode(&reqs)
   297  	} else {
   298  		batch = false
   299  		reqs = make([]jsonrpcCall, 1)
   300  		dec.Decode(&reqs[0])
   301  	}
   302  
   303  	// Execute the requests.
   304  	resps, _ := call.Otto.Object("new Array()")
   305  	for _, req := range reqs {
   306  		resp, _ := call.Otto.Object(`({"jsonrpc":"2.0"})`)
   307  		resp.Set("id", req.Id)
   308  		var result json.RawMessage
   309  		err = b.client.Call(&result, req.Method, req.Params...)
   310  		switch err := err.(type) {
   311  		case nil:
   312  			if result == nil {
   313  				// Special case null because it is decoded as an empty
   314  				// raw message for some reason.
   315  				resp.Set("result", otto.NullValue())
   316  			} else {
   317  				resultVal, err := JSON.Call("parse", string(result))
   318  				if err != nil {
   319  					setError(resp, -32603, err.Error())
   320  				} else {
   321  					resp.Set("result", resultVal)
   322  				}
   323  			}
   324  		case rpc.Error:
   325  			setError(resp, err.ErrorCode(), err.Error())
   326  		default:
   327  			setError(resp, -32603, err.Error())
   328  		}
   329  		resps.Call("push", resp)
   330  	}
   331  
   332  	// Return the responses either to the callback (if supplied)
   333  	// or directly as the return value.
   334  	if batch {
   335  		response = resps.Value()
   336  	} else {
   337  		response, _ = resps.Get("0")
   338  	}
   339  	if fn := call.Argument(1); fn.Class() == "Function" {
   340  		fn.Call(otto.NullValue(), otto.NullValue(), response)
   341  		return otto.UndefinedValue()
   342  	}
   343  	return response
   344  }
   345  
   346  func setError(resp *otto.Object, code int, msg string) {
   347  	resp.Set("error", map[string]interface{}{"code": code, "message": msg})
   348  }
   349  
   350  // throwJSException panics on an otto.Value. The Otto VM will recover from the
   351  // Go panic and throw msg as a JavaScript error.
   352  func throwJSException(msg interface{}) otto.Value {
   353  	val, err := otto.ToValue(msg)
   354  	if err != nil {
   355  		log.Error("Failed to serialize JavaScript exception", "exception", msg, "err", err)
   356  	}
   357  	panic(val)
   358  }