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