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