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