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