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