github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/signer/rules/rules.go (about)

     1  // Copyright 2018 The go-simplechain Authors
     2  // This file is part of the go-simplechain library.
     3  //
     4  // The go-simplechain 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-simplechain 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-simplechain 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/bigzoro/my_simplechain/internal/ethapi"
    26  	"github.com/bigzoro/my_simplechain/log"
    27  	"github.com/bigzoro/my_simplechain/signer/core"
    28  	"github.com/bigzoro/my_simplechain/signer/rules/deps"
    29  	"github.com/bigzoro/my_simplechain/signer/storage"
    30  	"github.com/robertkrimen/otto"
    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 otto.FunctionCall) otto.Value {
    40  	output := []string{"JS:> "}
    41  	for _, argument := range call.ArgumentList {
    42  		output = append(output, fmt.Sprintf("%v", argument))
    43  	}
    44  	fmt.Fprintln(os.Stderr, strings.Join(output, " "))
    45  	return otto.Value{}
    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{}) (otto.Value, error) {
    74  
    75  	// Instantiate a fresh vm engine every time
    76  	vm := otto.New()
    77  
    78  	// Set the native callbacks
    79  	consoleObj, _ := vm.Get("console")
    80  	consoleObj.Object().Set("log", consoleOutput)
    81  	consoleObj.Object().Set("error", consoleOutput)
    82  
    83  	vm.Set("storage", struct{}{})
    84  	storageObj, _ := vm.Get("storage")
    85  	storageObj.Object().Set("put", func(call otto.FunctionCall) otto.Value {
    86  		key, val := call.Argument(0).String(), call.Argument(1).String()
    87  		if val == "" {
    88  			r.storage.Del(key)
    89  		} else {
    90  			r.storage.Put(key, val)
    91  		}
    92  		return otto.NullValue()
    93  	})
    94  	storageObj.Object().Set("get", func(call otto.FunctionCall) otto.Value {
    95  		goval, _ := r.storage.Get(call.Argument(0).String())
    96  		jsval, _ := otto.ToValue(goval)
    97  		return jsval
    98  	})
    99  	// Load bootstrap libraries
   100  	script, err := vm.Compile("bignumber.js", BigNumber_JS)
   101  	if err != nil {
   102  		log.Warn("Failed loading libraries", "err", err)
   103  		return otto.UndefinedValue(), err
   104  	}
   105  	vm.Run(script)
   106  
   107  	// Run the actual rule implementation
   108  	_, err = vm.Run(r.jsRules)
   109  	if err != nil {
   110  		log.Warn("Execution failed", "err", err)
   111  		return otto.UndefinedValue(), err
   112  	}
   113  
   114  	// And the actual call
   115  	// All calls are objects with the parameters being keys in that object.
   116  	// To provide additional insulation between js and go, we serialize it into JSON on the Go-side,
   117  	// and deserialize it on the JS side.
   118  
   119  	jsonbytes, err := json.Marshal(jsarg)
   120  	if err != nil {
   121  		log.Warn("failed marshalling data", "data", jsarg)
   122  		return otto.UndefinedValue(), err
   123  	}
   124  	// Now, we call foobar(JSON.parse(<jsondata>)).
   125  	var call string
   126  	if len(jsonbytes) > 0 {
   127  		call = fmt.Sprintf("%v(JSON.parse(%v))", jsfunc, string(jsonbytes))
   128  	} else {
   129  		call = fmt.Sprintf("%v()", jsfunc)
   130  	}
   131  	return vm.Run(call)
   132  }
   133  
   134  func (r *rulesetUI) checkApproval(jsfunc string, jsarg []byte, err error) (bool, error) {
   135  	if err != nil {
   136  		return false, err
   137  	}
   138  	v, err := r.execute(jsfunc, string(jsarg))
   139  	if err != nil {
   140  		log.Info("error occurred during execution", "error", err)
   141  		return false, err
   142  	}
   143  	result, err := v.ToString()
   144  	if err != nil {
   145  		log.Info("error occurred during response unmarshalling", "error", err)
   146  		return false, err
   147  	}
   148  	if result == "Approve" {
   149  		log.Info("Op approved")
   150  		return true, nil
   151  	} else if result == "Reject" {
   152  		log.Info("Op rejected")
   153  		return false, nil
   154  	}
   155  	return false, fmt.Errorf("unknown response")
   156  }
   157  
   158  func (r *rulesetUI) ApproveTx(request *core.SignTxRequest) (core.SignTxResponse, error) {
   159  	jsonreq, err := json.Marshal(request)
   160  	approved, err := r.checkApproval("ApproveTx", jsonreq, err)
   161  	if err != nil {
   162  		log.Info("Rule-based approval error, going to manual", "error", err)
   163  		return r.next.ApproveTx(request)
   164  	}
   165  
   166  	if approved {
   167  		return core.SignTxResponse{
   168  				Transaction: request.Transaction,
   169  				Approved:    true},
   170  			nil
   171  	}
   172  	return core.SignTxResponse{Approved: false}, err
   173  }
   174  
   175  func (r *rulesetUI) ApproveSignData(request *core.SignDataRequest) (core.SignDataResponse, error) {
   176  	jsonreq, err := json.Marshal(request)
   177  	approved, err := r.checkApproval("ApproveSignData", jsonreq, err)
   178  	if err != nil {
   179  		log.Info("Rule-based approval error, going to manual", "error", err)
   180  		return r.next.ApproveSignData(request)
   181  	}
   182  	if approved {
   183  		return core.SignDataResponse{Approved: true}, nil
   184  	}
   185  	return core.SignDataResponse{Approved: false}, err
   186  }
   187  
   188  // OnInputRequired not handled by rules
   189  func (r *rulesetUI) OnInputRequired(info core.UserInputRequest) (core.UserInputResponse, error) {
   190  	return r.next.OnInputRequired(info)
   191  }
   192  
   193  func (r *rulesetUI) ApproveListing(request *core.ListRequest) (core.ListResponse, error) {
   194  	jsonreq, err := json.Marshal(request)
   195  	approved, err := r.checkApproval("ApproveListing", jsonreq, err)
   196  	if err != nil {
   197  		log.Info("Rule-based approval error, going to manual", "error", err)
   198  		return r.next.ApproveListing(request)
   199  	}
   200  	if approved {
   201  		return core.ListResponse{Accounts: request.Accounts}, nil
   202  	}
   203  	return core.ListResponse{}, err
   204  }
   205  
   206  func (r *rulesetUI) ApproveNewAccount(request *core.NewAccountRequest) (core.NewAccountResponse, error) {
   207  	// This cannot be handled by rules, requires setting a password
   208  	// dispatch to next
   209  	return r.next.ApproveNewAccount(request)
   210  }
   211  
   212  func (r *rulesetUI) ShowError(message string) {
   213  	log.Error(message)
   214  	r.next.ShowError(message)
   215  }
   216  
   217  func (r *rulesetUI) ShowInfo(message string) {
   218  	log.Info(message)
   219  	r.next.ShowInfo(message)
   220  }
   221  
   222  func (r *rulesetUI) OnSignerStartup(info core.StartupInfo) {
   223  	jsonInfo, err := json.Marshal(info)
   224  	if err != nil {
   225  		log.Warn("failed marshalling data", "data", info)
   226  		return
   227  	}
   228  	r.next.OnSignerStartup(info)
   229  	_, err = r.execute("OnSignerStartup", string(jsonInfo))
   230  	if err != nil {
   231  		log.Info("error occurred during execution", "error", err)
   232  	}
   233  }
   234  
   235  func (r *rulesetUI) OnApprovedTx(tx ethapi.SignTransactionResult) {
   236  	jsonTx, err := json.Marshal(tx)
   237  	if err != nil {
   238  		log.Warn("failed marshalling transaction", "tx", tx)
   239  		return
   240  	}
   241  	_, err = r.execute("OnApprovedTx", string(jsonTx))
   242  	if err != nil {
   243  		log.Info("error occurred during execution", "error", err)
   244  	}
   245  }