github.com/theQRL/go-zond@v0.1.1/signer/rules/rules.go (about)

     1  // Copyright 2018 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 rules
    18  
    19  import (
    20  	"encoding/json"
    21  	"errors"
    22  	"fmt"
    23  	"os"
    24  	"strings"
    25  
    26  	"github.com/dop251/goja"
    27  	"github.com/theQRL/go-zond/internal/ethapi"
    28  	"github.com/theQRL/go-zond/internal/jsre/deps"
    29  	"github.com/theQRL/go-zond/log"
    30  	"github.com/theQRL/go-zond/signer/core"
    31  	"github.com/theQRL/go-zond/signer/storage"
    32  )
    33  
    34  // consoleOutput is an override for the console.log and console.error methods to
    35  // stream the output into the configured output stream instead of stdout.
    36  func consoleOutput(call goja.FunctionCall) goja.Value {
    37  	output := []string{"JS:> "}
    38  	for _, argument := range call.Arguments {
    39  		output = append(output, fmt.Sprintf("%v", argument))
    40  	}
    41  	fmt.Fprintln(os.Stderr, strings.Join(output, " "))
    42  	return goja.Undefined()
    43  }
    44  
    45  // rulesetUI provides an implementation of UIClientAPI that evaluates a javascript
    46  // file for each defined UI-method
    47  type rulesetUI struct {
    48  	next    core.UIClientAPI // The next handler, for manual processing
    49  	storage storage.Storage
    50  	jsRules string // The rules to use
    51  }
    52  
    53  func NewRuleEvaluator(next core.UIClientAPI, jsbackend storage.Storage) (*rulesetUI, error) {
    54  	c := &rulesetUI{
    55  		next:    next,
    56  		storage: jsbackend,
    57  		jsRules: "",
    58  	}
    59  
    60  	return c, nil
    61  }
    62  func (r *rulesetUI) RegisterUIServer(api *core.UIServerAPI) {
    63  	r.next.RegisterUIServer(api)
    64  	// TODO, make it possible to query from js
    65  }
    66  
    67  func (r *rulesetUI) Init(javascriptRules string) error {
    68  	r.jsRules = javascriptRules
    69  	return nil
    70  }
    71  func (r *rulesetUI) execute(jsfunc string, jsarg interface{}) (goja.Value, error) {
    72  	// Instantiate a fresh vm engine every time
    73  	vm := goja.New()
    74  
    75  	// Set the native callbacks
    76  	consoleObj := vm.NewObject()
    77  	consoleObj.Set("log", consoleOutput)
    78  	consoleObj.Set("error", consoleOutput)
    79  	vm.Set("console", consoleObj)
    80  
    81  	storageObj := vm.NewObject()
    82  	storageObj.Set("put", func(call goja.FunctionCall) goja.Value {
    83  		key, val := call.Argument(0).String(), call.Argument(1).String()
    84  		if val == "" {
    85  			r.storage.Del(key)
    86  		} else {
    87  			r.storage.Put(key, val)
    88  		}
    89  		return goja.Null()
    90  	})
    91  	storageObj.Set("get", func(call goja.FunctionCall) goja.Value {
    92  		goval, _ := r.storage.Get(call.Argument(0).String())
    93  		jsval := vm.ToValue(goval)
    94  		return jsval
    95  	})
    96  	vm.Set("storage", storageObj)
    97  
    98  	// Load bootstrap libraries
    99  	script, err := goja.Compile("bignumber.js", deps.BigNumberJS, true)
   100  	if err != nil {
   101  		log.Warn("Failed loading libraries", "err", err)
   102  		return goja.Undefined(), err
   103  	}
   104  	vm.RunProgram(script)
   105  
   106  	// Run the actual rule implementation
   107  	_, err = vm.RunString(r.jsRules)
   108  	if err != nil {
   109  		log.Warn("Execution failed", "err", err)
   110  		return goja.Undefined(), err
   111  	}
   112  
   113  	// And the actual call
   114  	// All calls are objects with the parameters being keys in that object.
   115  	// To provide additional insulation between js and go, we serialize it into JSON on the Go-side,
   116  	// and deserialize it on the JS side.
   117  
   118  	jsonbytes, err := json.Marshal(jsarg)
   119  	if err != nil {
   120  		log.Warn("failed marshalling data", "data", jsarg)
   121  		return goja.Undefined(), err
   122  	}
   123  	// Now, we call foobar(JSON.parse(<jsondata>)).
   124  	var call string
   125  	if len(jsonbytes) > 0 {
   126  		call = fmt.Sprintf("%v(JSON.parse(%v))", jsfunc, string(jsonbytes))
   127  	} else {
   128  		call = fmt.Sprintf("%v()", jsfunc)
   129  	}
   130  	return vm.RunString(call)
   131  }
   132  
   133  func (r *rulesetUI) checkApproval(jsfunc string, jsarg []byte, err error) (bool, error) {
   134  	if err != nil {
   135  		return false, err
   136  	}
   137  	v, err := r.execute(jsfunc, string(jsarg))
   138  	if err != nil {
   139  		log.Info("error occurred during execution", "error", err)
   140  		return false, err
   141  	}
   142  	result := v.ToString().String()
   143  	if result == "Approve" {
   144  		log.Info("Op approved")
   145  		return true, nil
   146  	} else if result == "Reject" {
   147  		log.Info("Op rejected")
   148  		return false, nil
   149  	}
   150  	return false, errors.New("unknown response")
   151  }
   152  
   153  func (r *rulesetUI) ApproveTx(request *core.SignTxRequest) (core.SignTxResponse, error) {
   154  	jsonreq, err := json.Marshal(request)
   155  	approved, err := r.checkApproval("ApproveTx", jsonreq, err)
   156  	if err != nil {
   157  		log.Info("Rule-based approval error, going to manual", "error", err)
   158  		return r.next.ApproveTx(request)
   159  	}
   160  
   161  	if approved {
   162  		return core.SignTxResponse{
   163  				Transaction: request.Transaction,
   164  				Approved:    true},
   165  			nil
   166  	}
   167  	return core.SignTxResponse{Approved: false}, err
   168  }
   169  
   170  func (r *rulesetUI) ApproveSignData(request *core.SignDataRequest) (core.SignDataResponse, error) {
   171  	jsonreq, err := json.Marshal(request)
   172  	approved, err := r.checkApproval("ApproveSignData", jsonreq, err)
   173  	if err != nil {
   174  		log.Info("Rule-based approval error, going to manual", "error", err)
   175  		return r.next.ApproveSignData(request)
   176  	}
   177  	if approved {
   178  		return core.SignDataResponse{Approved: true}, nil
   179  	}
   180  	return core.SignDataResponse{Approved: false}, err
   181  }
   182  
   183  // OnInputRequired not handled by rules
   184  func (r *rulesetUI) OnInputRequired(info core.UserInputRequest) (core.UserInputResponse, error) {
   185  	return r.next.OnInputRequired(info)
   186  }
   187  
   188  func (r *rulesetUI) ApproveListing(request *core.ListRequest) (core.ListResponse, error) {
   189  	jsonreq, err := json.Marshal(request)
   190  	approved, err := r.checkApproval("ApproveListing", jsonreq, err)
   191  	if err != nil {
   192  		log.Info("Rule-based approval error, going to manual", "error", err)
   193  		return r.next.ApproveListing(request)
   194  	}
   195  	if approved {
   196  		return core.ListResponse{Accounts: request.Accounts}, nil
   197  	}
   198  	return core.ListResponse{}, err
   199  }
   200  
   201  func (r *rulesetUI) ApproveNewAccount(request *core.NewAccountRequest) (core.NewAccountResponse, error) {
   202  	// This cannot be handled by rules, requires setting a password
   203  	// dispatch to next
   204  	return r.next.ApproveNewAccount(request)
   205  }
   206  
   207  func (r *rulesetUI) ShowError(message string) {
   208  	log.Error(message)
   209  	r.next.ShowError(message)
   210  }
   211  
   212  func (r *rulesetUI) ShowInfo(message string) {
   213  	log.Info(message)
   214  	r.next.ShowInfo(message)
   215  }
   216  
   217  func (r *rulesetUI) OnSignerStartup(info core.StartupInfo) {
   218  	jsonInfo, err := json.Marshal(info)
   219  	if err != nil {
   220  		log.Warn("failed marshalling data", "data", info)
   221  		return
   222  	}
   223  	r.next.OnSignerStartup(info)
   224  	_, err = r.execute("OnSignerStartup", string(jsonInfo))
   225  	if err != nil {
   226  		log.Info("error occurred during execution", "error", err)
   227  	}
   228  }
   229  
   230  func (r *rulesetUI) OnApprovedTx(tx ethapi.SignTransactionResult) {
   231  	jsonTx, err := json.Marshal(tx)
   232  	if err != nil {
   233  		log.Warn("failed marshalling transaction", "tx", tx)
   234  		return
   235  	}
   236  	_, err = r.execute("OnApprovedTx", string(jsonTx))
   237  	if err != nil {
   238  		log.Info("error occurred during execution", "error", err)
   239  	}
   240  }