github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/signer/rules/rules.go (about)

     1  //  Copyright 2018 The go-ethereum Authors
     2  //  Copyright 2019 The go-aigar Authors
     3  //  This file is part of the go-aigar library.
     4  //
     5  //  The go-aigar library is free software: you can redistribute it and/or modify
     6  //  it under the terms of the GNU Lesser General Public License as published by
     7  //  the Free Software Foundation, either version 3 of the License, or
     8  //  (at your option) any later version.
     9  //
    10  //  The go-aigar library is distributed in the hope that it will be useful,
    11  //  but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  //  GNU Lesser General Public License for more details.
    14  //
    15  //  You should have received a copy of the GNU Lesser General Public License
    16  //  along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package rules
    19  
    20  import (
    21  	"encoding/json"
    22  	"fmt"
    23  	"os"
    24  	"strings"
    25  
    26  	"github.com/AigarNetwork/aigar/internal/ethapi"
    27  	"github.com/AigarNetwork/aigar/log"
    28  	"github.com/AigarNetwork/aigar/signer/core"
    29  	"github.com/AigarNetwork/aigar/signer/rules/deps"
    30  	"github.com/AigarNetwork/aigar/signer/storage"
    31  	"github.com/robertkrimen/otto"
    32  )
    33  
    34  var (
    35  	BigNumber_JS = deps.MustAsset("bignumber.js")
    36  )
    37  
    38  // consoleOutput is an override for the console.log and console.error methods to
    39  // stream the output into the configured output stream instead of stdout.
    40  func consoleOutput(call otto.FunctionCall) otto.Value {
    41  	output := []string{"JS:> "}
    42  	for _, argument := range call.ArgumentList {
    43  		output = append(output, fmt.Sprintf("%v", argument))
    44  	}
    45  	fmt.Fprintln(os.Stderr, strings.Join(output, " "))
    46  	return otto.Value{}
    47  }
    48  
    49  // rulesetUI provides an implementation of UIClientAPI that evaluates a javascript
    50  // file for each defined UI-method
    51  type rulesetUI struct {
    52  	next    core.UIClientAPI // The next handler, for manual processing
    53  	storage storage.Storage
    54  	jsRules string // The rules to use
    55  }
    56  
    57  func NewRuleEvaluator(next core.UIClientAPI, jsbackend storage.Storage) (*rulesetUI, error) {
    58  	c := &rulesetUI{
    59  		next:    next,
    60  		storage: jsbackend,
    61  		jsRules: "",
    62  	}
    63  
    64  	return c, nil
    65  }
    66  func (r *rulesetUI) RegisterUIServer(api *core.UIServerAPI) {
    67  	// TODO, make it possible to query from js
    68  }
    69  
    70  func (r *rulesetUI) Init(javascriptRules string) error {
    71  	r.jsRules = javascriptRules
    72  	return nil
    73  }
    74  func (r *rulesetUI) execute(jsfunc string, jsarg interface{}) (otto.Value, error) {
    75  
    76  	// Instantiate a fresh vm engine every time
    77  	vm := otto.New()
    78  
    79  	// Set the native callbacks
    80  	consoleObj, _ := vm.Get("console")
    81  	consoleObj.Object().Set("log", consoleOutput)
    82  	consoleObj.Object().Set("error", consoleOutput)
    83  
    84  	vm.Set("storage", struct{}{})
    85  	storageObj, _ := vm.Get("storage")
    86  	storageObj.Object().Set("put", func(call otto.FunctionCall) otto.Value {
    87  		key, val := call.Argument(0).String(), call.Argument(1).String()
    88  		if val == "" {
    89  			r.storage.Del(key)
    90  		} else {
    91  			r.storage.Put(key, val)
    92  		}
    93  		return otto.NullValue()
    94  	})
    95  	storageObj.Object().Set("get", func(call otto.FunctionCall) otto.Value {
    96  		goval, _ := r.storage.Get(call.Argument(0).String())
    97  		jsval, _ := otto.ToValue(goval)
    98  		return jsval
    99  	})
   100  	// Load bootstrap libraries
   101  	script, err := vm.Compile("bignumber.js", BigNumber_JS)
   102  	if err != nil {
   103  		log.Warn("Failed loading libraries", "err", err)
   104  		return otto.UndefinedValue(), err
   105  	}
   106  	vm.Run(script)
   107  
   108  	// Run the actual rule implementation
   109  	_, err = vm.Run(r.jsRules)
   110  	if err != nil {
   111  		log.Warn("Execution failed", "err", err)
   112  		return otto.UndefinedValue(), 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 otto.UndefinedValue(), 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.Run(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, err := v.ToString()
   145  	if err != nil {
   146  		log.Info("error occurred during response unmarshalling", "error", err)
   147  		return false, err
   148  	}
   149  	if result == "Approve" {
   150  		log.Info("Op approved")
   151  		return true, nil
   152  	} else if result == "Reject" {
   153  		log.Info("Op rejected")
   154  		return false, nil
   155  	}
   156  	return false, fmt.Errorf("Unknown response")
   157  }
   158  
   159  func (r *rulesetUI) ApproveTx(request *core.SignTxRequest) (core.SignTxResponse, error) {
   160  	jsonreq, err := json.Marshal(request)
   161  	approved, err := r.checkApproval("ApproveTx", jsonreq, err)
   162  	if err != nil {
   163  		log.Info("Rule-based approval error, going to manual", "error", err)
   164  		return r.next.ApproveTx(request)
   165  	}
   166  
   167  	if approved {
   168  		return core.SignTxResponse{
   169  				Transaction: request.Transaction,
   170  				Approved:    true},
   171  			nil
   172  	}
   173  	return core.SignTxResponse{Approved: false}, err
   174  }
   175  
   176  func (r *rulesetUI) ApproveSignData(request *core.SignDataRequest) (core.SignDataResponse, error) {
   177  	jsonreq, err := json.Marshal(request)
   178  	approved, err := r.checkApproval("ApproveSignData", jsonreq, err)
   179  	if err != nil {
   180  		log.Info("Rule-based approval error, going to manual", "error", err)
   181  		return r.next.ApproveSignData(request)
   182  	}
   183  	if approved {
   184  		return core.SignDataResponse{Approved: true}, nil
   185  	}
   186  	return core.SignDataResponse{Approved: false}, err
   187  }
   188  
   189  // OnInputRequired not handled by rules
   190  func (r *rulesetUI) OnInputRequired(info core.UserInputRequest) (core.UserInputResponse, error) {
   191  	return r.next.OnInputRequired(info)
   192  }
   193  
   194  func (r *rulesetUI) ApproveListing(request *core.ListRequest) (core.ListResponse, error) {
   195  	jsonreq, err := json.Marshal(request)
   196  	approved, err := r.checkApproval("ApproveListing", jsonreq, err)
   197  	if err != nil {
   198  		log.Info("Rule-based approval error, going to manual", "error", err)
   199  		return r.next.ApproveListing(request)
   200  	}
   201  	if approved {
   202  		return core.ListResponse{Accounts: request.Accounts}, nil
   203  	}
   204  	return core.ListResponse{}, err
   205  }
   206  
   207  func (r *rulesetUI) ApproveNewAccount(request *core.NewAccountRequest) (core.NewAccountResponse, error) {
   208  	// This cannot be handled by rules, requires setting a password
   209  	// dispatch to next
   210  	return r.next.ApproveNewAccount(request)
   211  }
   212  
   213  func (r *rulesetUI) ShowError(message string) {
   214  	log.Error(message)
   215  	r.next.ShowError(message)
   216  }
   217  
   218  func (r *rulesetUI) ShowInfo(message string) {
   219  	log.Info(message)
   220  	r.next.ShowInfo(message)
   221  }
   222  
   223  func (r *rulesetUI) OnSignerStartup(info core.StartupInfo) {
   224  	jsonInfo, err := json.Marshal(info)
   225  	if err != nil {
   226  		log.Warn("failed marshalling data", "data", info)
   227  		return
   228  	}
   229  	r.next.OnSignerStartup(info)
   230  	_, err = r.execute("OnSignerStartup", string(jsonInfo))
   231  	if err != nil {
   232  		log.Info("error occurred during execution", "error", err)
   233  	}
   234  }
   235  
   236  func (r *rulesetUI) OnApprovedTx(tx ethapi.SignTransactionResult) {
   237  	jsonTx, err := json.Marshal(tx)
   238  	if err != nil {
   239  		log.Warn("failed marshalling transaction", "tx", tx)
   240  		return
   241  	}
   242  	_, err = r.execute("OnApprovedTx", string(jsonTx))
   243  	if err != nil {
   244  		log.Info("error occurred during execution", "error", err)
   245  	}
   246  }