github.com/jincm/wesharechain@v0.0.0-20210122032815-1537409ce26a/chain/signer/rules/rules.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // This file is part of go-ethereum. 3 // 4 // go-ethereum is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU 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 // go-ethereum 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 General Public License for more details. 13 // 14 // You should have received a copy of the GNU General Public License 15 // along with go-ethereum. 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/ethereum/go-ethereum/common" 26 "github.com/ethereum/go-ethereum/internal/ethapi" 27 "github.com/ethereum/go-ethereum/log" 28 "github.com/ethereum/go-ethereum/signer/core" 29 "github.com/ethereum/go-ethereum/signer/rules/deps" 30 "github.com/ethereum/go-ethereum/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.Stdout, 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 credentials storage.Storage 55 jsRules string // The rules to use 56 } 57 58 func NewRuleEvaluator(next core.UIClientAPI, jsbackend, credentialsBackend storage.Storage) (*rulesetUI, error) { 59 c := &rulesetUI{ 60 next: next, 61 storage: jsbackend, 62 credentials: credentialsBackend, 63 jsRules: "", 64 } 65 66 return c, nil 67 } 68 func (r *rulesetUI) RegisterUIServer(api *core.UIServerAPI) { 69 // TODO, make it possible to query from js 70 } 71 72 func (r *rulesetUI) Init(javascriptRules string) error { 73 r.jsRules = javascriptRules 74 return nil 75 } 76 func (r *rulesetUI) execute(jsfunc string, jsarg interface{}) (otto.Value, error) { 77 78 // Instantiate a fresh vm engine every time 79 vm := otto.New() 80 // Set the native callbacks 81 consoleObj, _ := vm.Get("console") 82 consoleObj.Object().Set("log", consoleOutput) 83 consoleObj.Object().Set("error", consoleOutput) 84 vm.Set("storage", r.storage) 85 86 // Load bootstrap libraries 87 script, err := vm.Compile("bignumber.js", BigNumber_JS) 88 if err != nil { 89 log.Warn("Failed loading libraries", "err", err) 90 return otto.UndefinedValue(), err 91 } 92 vm.Run(script) 93 94 // Run the actual rule implementation 95 _, err = vm.Run(r.jsRules) 96 if err != nil { 97 log.Warn("Execution failed", "err", err) 98 return otto.UndefinedValue(), err 99 } 100 101 // And the actual call 102 // All calls are objects with the parameters being keys in that object. 103 // To provide additional insulation between js and go, we serialize it into JSON on the Go-side, 104 // and deserialize it on the JS side. 105 106 jsonbytes, err := json.Marshal(jsarg) 107 if err != nil { 108 log.Warn("failed marshalling data", "data", jsarg) 109 return otto.UndefinedValue(), err 110 } 111 // Now, we call foobar(JSON.parse(<jsondata>)). 112 var call string 113 if len(jsonbytes) > 0 { 114 call = fmt.Sprintf("%v(JSON.parse(%v))", jsfunc, string(jsonbytes)) 115 } else { 116 call = fmt.Sprintf("%v()", jsfunc) 117 } 118 return vm.Run(call) 119 } 120 121 func (r *rulesetUI) checkApproval(jsfunc string, jsarg []byte, err error) (bool, error) { 122 if err != nil { 123 return false, err 124 } 125 v, err := r.execute(jsfunc, string(jsarg)) 126 if err != nil { 127 log.Info("error occurred during execution", "error", err) 128 return false, err 129 } 130 result, err := v.ToString() 131 if err != nil { 132 log.Info("error occurred during response unmarshalling", "error", err) 133 return false, err 134 } 135 if result == "Approve" { 136 log.Info("Op approved") 137 return true, nil 138 } else if result == "Reject" { 139 log.Info("Op rejected") 140 return false, nil 141 } 142 return false, fmt.Errorf("Unknown response") 143 } 144 145 func (r *rulesetUI) ApproveTx(request *core.SignTxRequest) (core.SignTxResponse, error) { 146 jsonreq, err := json.Marshal(request) 147 approved, err := r.checkApproval("ApproveTx", jsonreq, err) 148 if err != nil { 149 log.Info("Rule-based approval error, going to manual", "error", err) 150 return r.next.ApproveTx(request) 151 } 152 153 if approved { 154 return core.SignTxResponse{ 155 Transaction: request.Transaction, 156 Approved: true, 157 Password: r.lookupPassword(request.Transaction.From.Address()), 158 }, 159 nil 160 } 161 return core.SignTxResponse{Approved: false}, err 162 } 163 164 func (r *rulesetUI) lookupPassword(address common.Address) string { 165 return r.credentials.Get(strings.ToLower(address.String())) 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, Password: r.lookupPassword(request.Address.Address())}, nil 177 } 178 return core.SignDataResponse{Approved: false, Password: ""}, err 179 } 180 181 func (r *rulesetUI) ApproveExport(request *core.ExportRequest) (core.ExportResponse, error) { 182 jsonreq, err := json.Marshal(request) 183 approved, err := r.checkApproval("ApproveExport", jsonreq, err) 184 if err != nil { 185 log.Info("Rule-based approval error, going to manual", "error", err) 186 return r.next.ApproveExport(request) 187 } 188 if approved { 189 return core.ExportResponse{Approved: true}, nil 190 } 191 return core.ExportResponse{Approved: false}, err 192 } 193 194 func (r *rulesetUI) ApproveImport(request *core.ImportRequest) (core.ImportResponse, error) { 195 // This cannot be handled by rules, requires setting a password 196 // dispatch to next 197 return r.next.ApproveImport(request) 198 } 199 200 // OnInputRequired not handled by rules 201 func (r *rulesetUI) OnInputRequired(info core.UserInputRequest) (core.UserInputResponse, error) { 202 return r.next.OnInputRequired(info) 203 } 204 205 func (r *rulesetUI) ApproveListing(request *core.ListRequest) (core.ListResponse, error) { 206 jsonreq, err := json.Marshal(request) 207 approved, err := r.checkApproval("ApproveListing", jsonreq, err) 208 if err != nil { 209 log.Info("Rule-based approval error, going to manual", "error", err) 210 return r.next.ApproveListing(request) 211 } 212 if approved { 213 return core.ListResponse{Accounts: request.Accounts}, nil 214 } 215 return core.ListResponse{}, err 216 } 217 218 func (r *rulesetUI) ApproveNewAccount(request *core.NewAccountRequest) (core.NewAccountResponse, error) { 219 // This cannot be handled by rules, requires setting a password 220 // dispatch to next 221 return r.next.ApproveNewAccount(request) 222 } 223 224 func (r *rulesetUI) ShowError(message string) { 225 log.Error(message) 226 r.next.ShowError(message) 227 } 228 229 func (r *rulesetUI) ShowInfo(message string) { 230 log.Info(message) 231 r.next.ShowInfo(message) 232 } 233 234 func (r *rulesetUI) OnSignerStartup(info core.StartupInfo) { 235 jsonInfo, err := json.Marshal(info) 236 if err != nil { 237 log.Warn("failed marshalling data", "data", info) 238 return 239 } 240 r.next.OnSignerStartup(info) 241 _, err = r.execute("OnSignerStartup", string(jsonInfo)) 242 if err != nil { 243 log.Info("error occurred during execution", "error", err) 244 } 245 } 246 247 func (r *rulesetUI) OnApprovedTx(tx ethapi.SignTransactionResult) { 248 jsonTx, err := json.Marshal(tx) 249 if err != nil { 250 log.Warn("failed marshalling transaction", "tx", tx) 251 return 252 } 253 _, err = r.execute("OnApprovedTx", string(jsonTx)) 254 if err != nil { 255 log.Info("error occurred during execution", "error", err) 256 } 257 }