github.com/core-coin/go-core/v2@v2.1.9/signer/rules/rules.go (about)

     1  // Copyright 2018 by the Authors
     2  // This file is part of the go-core library.
     3  //
     4  // The go-core 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-core 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-core 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  
    27  	"github.com/core-coin/go-core/v2/internal/xcbapi"
    28  
    29  	"github.com/core-coin/go-core/v2/log"
    30  	"github.com/core-coin/go-core/v2/signer/core"
    31  	"github.com/core-coin/go-core/v2/signer/rules/deps"
    32  	"github.com/core-coin/go-core/v2/signer/storage"
    33  )
    34  
    35  var (
    36  	BigNumber_JS = deps.MustAsset("bignumber.js")
    37  )
    38  
    39  // consoleOutput is an override for the console.log and console.error methods to
    40  // stream the output into the configured output stream instead of stdout.
    41  func consoleOutput(call goja.FunctionCall) goja.Value {
    42  	output := []string{"JS:> "}
    43  	for _, argument := range call.Arguments {
    44  		output = append(output, fmt.Sprintf("%v", argument))
    45  	}
    46  	fmt.Fprintln(os.Stderr, strings.Join(output, " "))
    47  	return goja.Undefined()
    48  }
    49  
    50  // rulesetUI provides an implementation of UIClientAPI that evaluates a javascript
    51  // file for each defined UI-method
    52  type rulesetUI struct {
    53  	next    core.UIClientAPI // The next handler, for manual processing
    54  	storage storage.Storage
    55  	jsRules string // The rules to use
    56  }
    57  
    58  func NewRuleEvaluator(next core.UIClientAPI, jsbackend storage.Storage) (*rulesetUI, error) {
    59  	c := &rulesetUI{
    60  		next:    next,
    61  		storage: jsbackend,
    62  		jsRules: "",
    63  	}
    64  
    65  	return c, nil
    66  }
    67  func (r *rulesetUI) RegisterUIServer(api *core.UIServerAPI) {
    68  	// TODO, make it possible to query from js
    69  }
    70  
    71  func (r *rulesetUI) Init(javascriptRules string) error {
    72  	r.jsRules = javascriptRules
    73  	return nil
    74  }
    75  func (r *rulesetUI) execute(jsfunc string, jsarg interface{}) (goja.Value, error) {
    76  
    77  	// Instantiate a fresh vm engine every time
    78  	vm := goja.New()
    79  
    80  	// Set the native callbacks
    81  	consoleObj := vm.NewObject()
    82  	consoleObj.Set("log", consoleOutput)
    83  	consoleObj.Set("error", consoleOutput)
    84  	vm.Set("console", consoleObj)
    85  
    86  	storageObj := vm.NewObject()
    87  	storageObj.Set("put", func(call goja.FunctionCall) goja.Value {
    88  		key, val := call.Argument(0).String(), call.Argument(1).String()
    89  		if val == "" {
    90  			r.storage.Del(key)
    91  		} else {
    92  			r.storage.Put(key, val)
    93  		}
    94  		return goja.Null()
    95  	})
    96  	storageObj.Set("get", func(call goja.FunctionCall) goja.Value {
    97  		goval, _ := r.storage.Get(call.Argument(0).String())
    98  		jsval := vm.ToValue(goval)
    99  		return jsval
   100  	})
   101  	vm.Set("storage", storageObj)
   102  
   103  	// Load bootstrap libraries
   104  	script, err := goja.Compile("bignumber.js", string(BigNumber_JS), true)
   105  	if err != nil {
   106  		log.Warn("Failed loading libraries", "err", err)
   107  		return goja.Undefined(), err
   108  	}
   109  	vm.RunProgram(script)
   110  
   111  	// Run the actual rule implementation
   112  	_, err = vm.RunString(r.jsRules)
   113  	if err != nil {
   114  		log.Warn("Execution failed", "err", err)
   115  		return goja.Undefined(), err
   116  	}
   117  
   118  	// And the actual call
   119  	// All calls are objects with the parameters being keys in that object.
   120  	// To provide additional insulation between js and go, we serialize it into JSON on the Go-side,
   121  	// and deserialize it on the JS side.
   122  
   123  	jsonbytes, err := json.Marshal(jsarg)
   124  	if err != nil {
   125  		log.Warn("failed marshalling data", "data", jsarg)
   126  		return goja.Undefined(), err
   127  	}
   128  	// Now, we call foobar(JSON.parse(<jsondata>)).
   129  	var call string
   130  	if len(jsonbytes) > 0 {
   131  		call = fmt.Sprintf("%v(JSON.parse(%v))", jsfunc, string(jsonbytes))
   132  	} else {
   133  		call = fmt.Sprintf("%v()", jsfunc)
   134  	}
   135  	return vm.RunString(call)
   136  }
   137  
   138  func (r *rulesetUI) checkApproval(jsfunc string, jsarg []byte, err error) (bool, error) {
   139  	if err != nil {
   140  		return false, err
   141  	}
   142  	v, err := r.execute(jsfunc, string(jsarg))
   143  	if err != nil {
   144  		log.Info("error occurred during execution", "error", err)
   145  		return false, err
   146  	}
   147  	result := v.ToString().String()
   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 xcbapi.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  }