2016-09-11 11:44:14 +00:00
|
|
|
package jail
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"sync"
|
|
|
|
|
2017-05-02 14:35:37 +00:00
|
|
|
"github.com/ethereum/go-ethereum/log"
|
2016-09-11 11:44:14 +00:00
|
|
|
"github.com/ethereum/go-ethereum/rpc"
|
|
|
|
"github.com/robertkrimen/otto"
|
2017-05-16 12:09:52 +00:00
|
|
|
"github.com/status-im/status-go/geth/common"
|
2017-04-06 19:36:55 +00:00
|
|
|
"github.com/status-im/status-go/static"
|
2017-07-13 11:04:47 +00:00
|
|
|
|
|
|
|
"fknsrs.biz/p/ottoext/loop"
|
2016-10-07 14:48:36 +00:00
|
|
|
)
|
|
|
|
|
2017-08-04 16:14:17 +00:00
|
|
|
// FIXME(tiabc): Get rid of this global variable. Move it to a constructor or initialization.
|
2017-05-16 12:09:52 +00:00
|
|
|
var web3JSCode = static.MustAsset("scripts/web3.js")
|
|
|
|
|
2017-05-03 14:24:48 +00:00
|
|
|
// errors
|
2016-09-11 11:44:14 +00:00
|
|
|
var (
|
|
|
|
ErrInvalidJail = errors.New("jail environment is not properly initialized")
|
|
|
|
)
|
|
|
|
|
2017-05-16 12:09:52 +00:00
|
|
|
// Jail represents jailed environment inside of which we hold multiple cells.
|
|
|
|
// Each cell is a separate JavaScript VM.
|
|
|
|
type Jail struct {
|
2017-08-07 10:48:14 +00:00
|
|
|
// FIXME(tiabc): This mutex handles cells field access and must be renamed appropriately: cellsMutex
|
2017-05-16 12:09:52 +00:00
|
|
|
sync.RWMutex
|
|
|
|
requestManager *RequestManager
|
2017-08-04 16:14:17 +00:00
|
|
|
cells map[string]*JailCell // jail supports running many isolated instances of jailed runtime
|
|
|
|
baseJSCode string // JavaScript used to initialize all new cells with
|
2017-07-13 11:04:47 +00:00
|
|
|
}
|
|
|
|
|
2017-08-04 16:14:17 +00:00
|
|
|
// New returns new Jail environment.
|
2017-05-16 12:09:52 +00:00
|
|
|
func New(nodeManager common.NodeManager) *Jail {
|
|
|
|
return &Jail{
|
2017-08-04 16:14:17 +00:00
|
|
|
cells: make(map[string]*JailCell),
|
2017-05-16 12:09:52 +00:00
|
|
|
requestManager: NewRequestManager(nodeManager),
|
|
|
|
}
|
2016-09-11 11:44:14 +00:00
|
|
|
}
|
|
|
|
|
2017-08-04 16:14:17 +00:00
|
|
|
// BaseJS allows to setup initial JavaScript to be loaded on each jail.Parse().
|
2017-05-16 12:09:52 +00:00
|
|
|
func (jail *Jail) BaseJS(js string) {
|
|
|
|
jail.baseJSCode = js
|
2016-09-11 11:44:14 +00:00
|
|
|
}
|
|
|
|
|
2017-08-04 16:14:17 +00:00
|
|
|
// NewJailCell initializes and returns jail cell.
|
|
|
|
func (jail *Jail) NewJailCell(id string) (common.JailCell, error) {
|
|
|
|
if jail == nil {
|
|
|
|
return nil, ErrInvalidJail
|
|
|
|
}
|
|
|
|
|
2017-07-13 11:04:47 +00:00
|
|
|
vm := otto.New()
|
|
|
|
|
|
|
|
newJail, err := newJailCell(id, vm, loop.New(vm))
|
|
|
|
if err != nil {
|
2017-08-04 16:14:17 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
jail.Lock()
|
|
|
|
jail.cells[id] = newJail
|
|
|
|
jail.Unlock()
|
|
|
|
|
|
|
|
return newJail, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetJailCell returns the associated *JailCell for the provided chatID.
|
|
|
|
func (jail *Jail) GetJailCell(chatID string) (common.JailCell, error) {
|
|
|
|
return jail.GetCell(chatID)
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetCell returns the associated *JailCell for the provided chatID.
|
|
|
|
func (jail *Jail) GetCell(chatID string) (*JailCell, error) {
|
|
|
|
jail.RLock()
|
|
|
|
defer jail.RUnlock()
|
|
|
|
|
|
|
|
cell, ok := jail.cells[chatID]
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("cell[%s] doesn't exist", chatID)
|
2016-10-07 14:48:36 +00:00
|
|
|
}
|
2017-07-13 11:04:47 +00:00
|
|
|
|
2017-08-04 16:14:17 +00:00
|
|
|
return cell, nil
|
2016-10-07 14:48:36 +00:00
|
|
|
}
|
|
|
|
|
2017-05-16 12:09:52 +00:00
|
|
|
// Parse creates a new jail cell context, with the given chatID as identifier.
|
2017-05-03 14:24:48 +00:00
|
|
|
// New context executes provided JavaScript code, right after the initialization.
|
|
|
|
func (jail *Jail) Parse(chatID string, js string) string {
|
2016-09-11 11:44:14 +00:00
|
|
|
if jail == nil {
|
2017-05-16 12:09:52 +00:00
|
|
|
return makeError(ErrInvalidJail.Error())
|
2016-09-11 11:44:14 +00:00
|
|
|
}
|
|
|
|
|
2017-08-04 16:14:17 +00:00
|
|
|
var err error
|
|
|
|
var jcell *JailCell
|
|
|
|
|
|
|
|
if jcell, err = jail.GetCell(chatID); err != nil {
|
|
|
|
if _, mkerr := jail.NewJailCell(chatID); mkerr != nil {
|
|
|
|
return makeError(mkerr.Error())
|
|
|
|
}
|
2016-10-13 18:02:48 +00:00
|
|
|
|
2017-08-04 16:14:17 +00:00
|
|
|
jcell, _ = jail.GetCell(chatID)
|
|
|
|
}
|
2016-10-07 14:48:36 +00:00
|
|
|
|
2017-08-04 16:14:17 +00:00
|
|
|
// init jeth and its handlers
|
|
|
|
if err = jcell.Set("jeth", struct{}{}); err != nil {
|
2017-05-16 12:09:52 +00:00
|
|
|
return makeError(err.Error())
|
2017-05-03 14:24:48 +00:00
|
|
|
}
|
2016-09-11 11:44:14 +00:00
|
|
|
|
2017-08-04 16:14:17 +00:00
|
|
|
if err = registerHandlers(jail, jcell, chatID); err != nil {
|
2017-05-16 12:09:52 +00:00
|
|
|
return makeError(err.Error())
|
2017-05-03 14:24:48 +00:00
|
|
|
}
|
2017-08-04 16:14:17 +00:00
|
|
|
|
|
|
|
initJs := jail.baseJSCode + ";"
|
|
|
|
if _, err = jcell.Run(initJs); err != nil {
|
2017-05-16 12:09:52 +00:00
|
|
|
return makeError(err.Error())
|
2017-05-03 14:24:48 +00:00
|
|
|
}
|
2016-11-28 18:30:25 +00:00
|
|
|
|
2017-07-18 14:26:24 +00:00
|
|
|
// sendMessage/showSuggestions handlers
|
2017-08-04 16:14:17 +00:00
|
|
|
jcell.Set("statusSignals", struct{}{})
|
|
|
|
statusSignals, _ := jcell.Get("statusSignals")
|
2017-07-18 14:26:24 +00:00
|
|
|
statusSignals.Object().Set("sendMessage", makeSendMessageHandler(chatID))
|
|
|
|
statusSignals.Object().Set("showSuggestions", makeShowSuggestionsHandler(chatID))
|
|
|
|
|
2017-05-16 12:09:52 +00:00
|
|
|
jjs := string(web3JSCode) + `
|
2016-09-11 11:44:14 +00:00
|
|
|
var Web3 = require('web3');
|
|
|
|
var web3 = new Web3(jeth);
|
|
|
|
var Bignumber = require("bignumber.js");
|
|
|
|
function bn(val){
|
|
|
|
return new Bignumber(val);
|
|
|
|
}
|
|
|
|
` + js + "; var catalog = JSON.stringify(_status_catalog);"
|
2017-08-04 16:14:17 +00:00
|
|
|
if _, err = jcell.Run(jjs); err != nil {
|
2017-05-16 12:09:52 +00:00
|
|
|
return makeError(err.Error())
|
2017-05-03 14:24:48 +00:00
|
|
|
}
|
2016-09-11 11:44:14 +00:00
|
|
|
|
2017-08-04 16:14:17 +00:00
|
|
|
res, err := jcell.Get("catalog")
|
2017-05-03 14:24:48 +00:00
|
|
|
if err != nil {
|
2017-05-16 12:09:52 +00:00
|
|
|
return makeError(err.Error())
|
2017-05-03 14:24:48 +00:00
|
|
|
}
|
2016-09-11 11:44:14 +00:00
|
|
|
|
2017-05-16 12:09:52 +00:00
|
|
|
return makeResult(res.String(), err)
|
2016-09-11 11:44:14 +00:00
|
|
|
}
|
|
|
|
|
2017-08-04 16:14:17 +00:00
|
|
|
// Call executes the `call` function w/i a jail cell context identified by the chatID.
|
2017-05-16 12:09:52 +00:00
|
|
|
// Jail cell is clonned before call is executed i.e. all calls execute w/i their own contexts.
|
2017-05-03 14:24:48 +00:00
|
|
|
func (jail *Jail) Call(chatID string, path string, args string) string {
|
2017-08-04 16:14:17 +00:00
|
|
|
jcell, err := jail.GetCell(chatID)
|
2017-07-13 11:04:47 +00:00
|
|
|
if err != nil {
|
|
|
|
return makeError(err.Error())
|
|
|
|
}
|
|
|
|
|
2017-08-04 16:14:17 +00:00
|
|
|
res, err := jcell.Call("call", nil, path, args)
|
2016-10-13 18:02:48 +00:00
|
|
|
|
2017-08-04 16:14:17 +00:00
|
|
|
// WARNING(influx6): We can have go-routine leakage due to continous call to this method
|
|
|
|
// and the call to cell.CellLoop().Run() due to improper usage, let's keep this
|
|
|
|
// in sight if things ever go wrong here.
|
|
|
|
// Due to the new event loop provided by ottoext.
|
|
|
|
// We need to ensure that all possible calls to internal setIntervals/SetTimeouts/SetImmediate
|
|
|
|
// work by lunching the loop.Run() method.
|
|
|
|
// Needs to be done in a go-routine.
|
|
|
|
go jcell.lo.Run()
|
2016-09-11 11:44:14 +00:00
|
|
|
|
2017-08-04 16:14:17 +00:00
|
|
|
return makeResult(res.String(), err)
|
2016-09-11 11:44:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Send will serialize the first argument, send it to the node and returns the response.
|
2017-05-03 14:24:48 +00:00
|
|
|
// nolint: errcheck, unparam
|
2017-08-04 16:14:17 +00:00
|
|
|
func (jail *Jail) Send(call otto.FunctionCall) (response otto.Value) {
|
2017-05-16 12:09:52 +00:00
|
|
|
client, err := jail.requestManager.RPCClient()
|
2016-10-07 14:48:36 +00:00
|
|
|
if err != nil {
|
2017-08-04 16:14:17 +00:00
|
|
|
return newErrorResponse(call.Otto, -32603, err.Error(), nil)
|
2016-10-07 14:48:36 +00:00
|
|
|
}
|
|
|
|
|
2016-09-11 11:44:14 +00:00
|
|
|
// Remarshal the request into a Go value.
|
|
|
|
JSON, _ := call.Otto.Object("JSON")
|
|
|
|
reqVal, err := JSON.Call("stringify", call.Argument(0))
|
|
|
|
if err != nil {
|
|
|
|
throwJSException(err.Error())
|
|
|
|
}
|
|
|
|
var (
|
|
|
|
rawReq = []byte(reqVal.String())
|
2017-05-16 12:09:52 +00:00
|
|
|
reqs []RPCCall
|
2016-12-18 20:36:17 +00:00
|
|
|
batch bool
|
2016-09-11 11:44:14 +00:00
|
|
|
)
|
|
|
|
if rawReq[0] == '[' {
|
|
|
|
batch = true
|
|
|
|
json.Unmarshal(rawReq, &reqs)
|
|
|
|
} else {
|
|
|
|
batch = false
|
2017-05-16 12:09:52 +00:00
|
|
|
reqs = make([]RPCCall, 1)
|
2016-09-11 11:44:14 +00:00
|
|
|
json.Unmarshal(rawReq, &reqs[0])
|
|
|
|
}
|
|
|
|
|
|
|
|
// Execute the requests.
|
|
|
|
resps, _ := call.Otto.Object("new Array()")
|
|
|
|
for _, req := range reqs {
|
|
|
|
resp, _ := call.Otto.Object(`({"jsonrpc":"2.0"})`)
|
2017-05-03 14:24:48 +00:00
|
|
|
resp.Set("id", req.ID)
|
2016-09-11 11:44:14 +00:00
|
|
|
var result json.RawMessage
|
|
|
|
|
2016-10-13 18:02:48 +00:00
|
|
|
// execute directly w/o RPC call to node
|
2017-05-16 12:09:52 +00:00
|
|
|
if req.Method == SendTransactionRequest {
|
|
|
|
txHash, err := jail.requestManager.ProcessSendTransactionRequest(call.Otto, req)
|
2016-10-13 18:02:48 +00:00
|
|
|
resp.Set("result", txHash.Hex())
|
|
|
|
if err != nil {
|
2017-08-04 16:14:17 +00:00
|
|
|
resp = newErrorResponse(call.Otto, -32603, err.Error(), &req.ID).Object()
|
2016-10-13 18:02:48 +00:00
|
|
|
}
|
|
|
|
resps.Call("push", resp)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2016-10-12 17:51:25 +00:00
|
|
|
// do extra request pre processing (persist message id)
|
|
|
|
// within function semaphore will be acquired and released,
|
|
|
|
// so that no more than one client (per cell) can enter
|
2017-05-16 12:09:52 +00:00
|
|
|
messageID, err := jail.requestManager.PreProcessRequest(call.Otto, req)
|
2016-10-12 17:51:25 +00:00
|
|
|
if err != nil {
|
2017-08-04 16:14:17 +00:00
|
|
|
return newErrorResponse(call.Otto, -32603, err.Error(), nil)
|
2016-10-12 17:51:25 +00:00
|
|
|
}
|
2016-10-07 14:48:36 +00:00
|
|
|
|
2016-09-11 11:44:14 +00:00
|
|
|
errc := make(chan error, 1)
|
|
|
|
errc2 := make(chan error)
|
|
|
|
go func() {
|
|
|
|
errc2 <- <-errc
|
|
|
|
}()
|
|
|
|
errc <- client.Call(&result, req.Method, req.Params...)
|
|
|
|
err = <-errc2
|
|
|
|
|
|
|
|
switch err := err.(type) {
|
|
|
|
case nil:
|
|
|
|
if result == nil {
|
|
|
|
// Special case null because it is decoded as an empty
|
|
|
|
// raw message for some reason.
|
|
|
|
resp.Set("result", otto.NullValue())
|
|
|
|
} else {
|
2017-05-03 14:24:48 +00:00
|
|
|
resultVal, callErr := JSON.Call("parse", string(result))
|
|
|
|
if callErr != nil {
|
2017-08-04 16:14:17 +00:00
|
|
|
resp = newErrorResponse(call.Otto, -32603, callErr.Error(), &req.ID).Object()
|
2016-09-11 11:44:14 +00:00
|
|
|
} else {
|
|
|
|
resp.Set("result", resultVal)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
case rpc.Error:
|
|
|
|
resp.Set("error", map[string]interface{}{
|
|
|
|
"code": err.ErrorCode(),
|
|
|
|
"message": err.Error(),
|
|
|
|
})
|
|
|
|
default:
|
2017-08-04 16:14:17 +00:00
|
|
|
resp = newErrorResponse(call.Otto, -32603, err.Error(), &req.ID).Object()
|
2016-09-11 11:44:14 +00:00
|
|
|
}
|
|
|
|
resps.Call("push", resp)
|
2016-10-12 17:51:25 +00:00
|
|
|
|
|
|
|
// do extra request post processing (setting back tx context)
|
2017-05-16 12:09:52 +00:00
|
|
|
jail.requestManager.PostProcessRequest(call.Otto, req, messageID)
|
2016-09-11 11:44:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Return the responses either to the callback (if supplied)
|
|
|
|
// or directly as the return value.
|
|
|
|
if batch {
|
|
|
|
response = resps.Value()
|
|
|
|
} else {
|
|
|
|
response, _ = resps.Get("0")
|
|
|
|
}
|
|
|
|
if fn := call.Argument(1); fn.Class() == "Function" {
|
|
|
|
fn.Call(otto.NullValue(), otto.NullValue(), response)
|
|
|
|
return otto.UndefinedValue()
|
|
|
|
}
|
|
|
|
return response
|
|
|
|
}
|
|
|
|
|
2017-08-04 16:14:17 +00:00
|
|
|
func newErrorResponse(otto *otto.Otto, code int, msg string, id interface{}) otto.Value {
|
2016-09-11 11:44:14 +00:00
|
|
|
// Bundle the error into a JSON RPC call response
|
2016-12-01 16:52:37 +00:00
|
|
|
m := map[string]interface{}{"jsonrpc": "2.0", "id": id, "error": map[string]interface{}{"code": code, msg: msg}}
|
2016-09-11 11:44:14 +00:00
|
|
|
res, _ := json.Marshal(m)
|
2017-08-04 16:14:17 +00:00
|
|
|
val, _ := otto.Run("(" + string(res) + ")")
|
2016-09-11 11:44:14 +00:00
|
|
|
return val
|
|
|
|
}
|
|
|
|
|
2017-08-04 16:14:17 +00:00
|
|
|
func newResultResponse(vm *otto.Otto, result interface{}) otto.Value {
|
|
|
|
resp, _ := vm.Object(`({"jsonrpc":"2.0"})`)
|
2017-05-03 14:24:48 +00:00
|
|
|
resp.Set("result", result) // nolint: errcheck
|
2016-12-18 20:36:17 +00:00
|
|
|
|
|
|
|
return resp.Value()
|
|
|
|
}
|
|
|
|
|
2016-09-11 11:44:14 +00:00
|
|
|
// throwJSException panics on an otto.Value. The Otto VM will recover from the
|
|
|
|
// Go panic and throw msg as a JavaScript error.
|
|
|
|
func throwJSException(msg interface{}) otto.Value {
|
|
|
|
val, err := otto.ToValue(msg)
|
|
|
|
if err != nil {
|
2017-05-02 14:35:37 +00:00
|
|
|
log.Error(fmt.Sprintf("Failed to serialize JavaScript exception %v: %v", msg, err))
|
2016-09-11 11:44:14 +00:00
|
|
|
}
|
|
|
|
panic(val)
|
|
|
|
}
|
|
|
|
|
2017-05-16 12:09:52 +00:00
|
|
|
// JSONError is wrapper around errors, that are sent upwards
|
|
|
|
type JSONError struct {
|
|
|
|
Error string `json:"error"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func makeError(error string) string {
|
|
|
|
str := JSONError{
|
2016-09-11 11:44:14 +00:00
|
|
|
Error: error,
|
|
|
|
}
|
|
|
|
outBytes, _ := json.Marshal(&str)
|
|
|
|
return string(outBytes)
|
|
|
|
}
|
|
|
|
|
2017-05-16 12:09:52 +00:00
|
|
|
func makeResult(res string, err error) string {
|
2016-09-11 11:44:14 +00:00
|
|
|
var out string
|
|
|
|
if err != nil {
|
2017-05-16 12:09:52 +00:00
|
|
|
out = makeError(err.Error())
|
2016-09-11 11:44:14 +00:00
|
|
|
} else {
|
|
|
|
if "undefined" == res {
|
|
|
|
res = "null"
|
|
|
|
}
|
|
|
|
out = fmt.Sprintf(`{"result": %s}`, res)
|
|
|
|
}
|
|
|
|
|
|
|
|
return out
|
|
|
|
}
|