github.com/palisadeinc/bor@v0.0.0-20230615125219-ab7196213d15/signer/rules/rules_test.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 "fmt" 21 "math/big" 22 "strings" 23 "testing" 24 25 "github.com/ethereum/go-ethereum/accounts" 26 "github.com/ethereum/go-ethereum/common" 27 "github.com/ethereum/go-ethereum/common/hexutil" 28 "github.com/ethereum/go-ethereum/core/types" 29 "github.com/ethereum/go-ethereum/internal/ethapi" 30 "github.com/ethereum/go-ethereum/signer/core" 31 "github.com/ethereum/go-ethereum/signer/core/apitypes" 32 "github.com/ethereum/go-ethereum/signer/storage" 33 ) 34 35 const JS = ` 36 /** 37 This is an example implementation of a Javascript rule file. 38 39 When the signer receives a request over the external API, the corresponding method is evaluated. 40 Three things can happen: 41 42 1. The method returns "Approve". This means the operation is permitted. 43 2. The method returns "Reject". This means the operation is rejected. 44 3. Anything else; other return values [*], method not implemented or exception occurred during processing. This means 45 that the operation will continue to manual processing, via the regular UI method chosen by the user. 46 47 [*] Note: Future version of the ruleset may use more complex json-based returnvalues, making it possible to not 48 only respond Approve/Reject/Manual, but also modify responses. For example, choose to list only one, but not all 49 accounts in a list-request. The points above will continue to hold for non-json based responses ("Approve"/"Reject"). 50 51 **/ 52 53 function ApproveListing(request){ 54 console.log("In js approve listing"); 55 console.log(request.accounts[3].Address) 56 console.log(request.meta.Remote) 57 return "Approve" 58 } 59 60 function ApproveTx(request){ 61 console.log("test"); 62 console.log("from"); 63 return "Reject"; 64 } 65 66 function test(thing){ 67 console.log(thing.String()) 68 } 69 70 ` 71 72 func mixAddr(a string) (*common.MixedcaseAddress, error) { 73 return common.NewMixedcaseAddressFromString(a) 74 } 75 76 type alwaysDenyUI struct{} 77 78 func (alwaysDenyUI) OnInputRequired(info core.UserInputRequest) (core.UserInputResponse, error) { 79 return core.UserInputResponse{}, nil 80 } 81 func (alwaysDenyUI) RegisterUIServer(api *core.UIServerAPI) { 82 } 83 84 func (alwaysDenyUI) OnSignerStartup(info core.StartupInfo) { 85 } 86 87 func (alwaysDenyUI) ApproveTx(request *core.SignTxRequest) (core.SignTxResponse, error) { 88 return core.SignTxResponse{Transaction: request.Transaction, Approved: false}, nil 89 } 90 91 func (alwaysDenyUI) ApproveSignData(request *core.SignDataRequest) (core.SignDataResponse, error) { 92 return core.SignDataResponse{Approved: false}, nil 93 } 94 95 func (alwaysDenyUI) ApproveListing(request *core.ListRequest) (core.ListResponse, error) { 96 return core.ListResponse{Accounts: nil}, nil 97 } 98 99 func (alwaysDenyUI) ApproveNewAccount(request *core.NewAccountRequest) (core.NewAccountResponse, error) { 100 return core.NewAccountResponse{Approved: false}, nil 101 } 102 103 func (alwaysDenyUI) ShowError(message string) { 104 panic("implement me") 105 } 106 107 func (alwaysDenyUI) ShowInfo(message string) { 108 panic("implement me") 109 } 110 111 func (alwaysDenyUI) OnApprovedTx(tx ethapi.SignTransactionResult) { 112 panic("implement me") 113 } 114 115 func initRuleEngine(js string) (*rulesetUI, error) { 116 r, err := NewRuleEvaluator(&alwaysDenyUI{}, storage.NewEphemeralStorage()) 117 if err != nil { 118 return nil, fmt.Errorf("failed to create js engine: %v", err) 119 } 120 if err = r.Init(js); err != nil { 121 return nil, fmt.Errorf("failed to load bootstrap js: %v", err) 122 } 123 return r, nil 124 } 125 126 func TestListRequest(t *testing.T) { 127 accs := make([]accounts.Account, 5) 128 129 for i := range accs { 130 addr := fmt.Sprintf("000000000000000000000000000000000000000%x", i) 131 acc := accounts.Account{ 132 Address: common.BytesToAddress(common.Hex2Bytes(addr)), 133 URL: accounts.URL{Scheme: "test", Path: fmt.Sprintf("acc-%d", i)}, 134 } 135 accs[i] = acc 136 } 137 138 js := `function ApproveListing(){ return "Approve" }` 139 140 r, err := initRuleEngine(js) 141 if err != nil { 142 t.Errorf("Couldn't create evaluator %v", err) 143 return 144 } 145 resp, _ := r.ApproveListing(&core.ListRequest{ 146 Accounts: accs, 147 Meta: core.Metadata{Remote: "remoteip", Local: "localip", Scheme: "inproc"}, 148 }) 149 if len(resp.Accounts) != len(accs) { 150 t.Errorf("Expected check to resolve to 'Approve'") 151 } 152 } 153 154 func TestSignTxRequest(t *testing.T) { 155 156 js := ` 157 function ApproveTx(r){ 158 console.log("transaction.from", r.transaction.from); 159 console.log("transaction.to", r.transaction.to); 160 console.log("transaction.value", r.transaction.value); 161 console.log("transaction.nonce", r.transaction.nonce); 162 if(r.transaction.from.toLowerCase()=="0x0000000000000000000000000000000000001337"){ return "Approve"} 163 if(r.transaction.from.toLowerCase()=="0x000000000000000000000000000000000000dead"){ return "Reject"} 164 }` 165 166 r, err := initRuleEngine(js) 167 if err != nil { 168 t.Errorf("Couldn't create evaluator %v", err) 169 return 170 } 171 to, err := mixAddr("000000000000000000000000000000000000dead") 172 if err != nil { 173 t.Error(err) 174 return 175 } 176 from, err := mixAddr("0000000000000000000000000000000000001337") 177 178 if err != nil { 179 t.Error(err) 180 return 181 } 182 t.Logf("to %v", to.Address().String()) 183 resp, err := r.ApproveTx(&core.SignTxRequest{ 184 Transaction: apitypes.SendTxArgs{ 185 From: *from, 186 To: to}, 187 Callinfo: nil, 188 Meta: core.Metadata{Remote: "remoteip", Local: "localip", Scheme: "inproc"}, 189 }) 190 if err != nil { 191 t.Errorf("Unexpected error %v", err) 192 } 193 if !resp.Approved { 194 t.Errorf("Expected check to resolve to 'Approve'") 195 } 196 } 197 198 type dummyUI struct { 199 calls []string 200 } 201 202 func (d *dummyUI) RegisterUIServer(api *core.UIServerAPI) { 203 panic("implement me") 204 } 205 206 func (d *dummyUI) OnInputRequired(info core.UserInputRequest) (core.UserInputResponse, error) { 207 d.calls = append(d.calls, "OnInputRequired") 208 return core.UserInputResponse{}, nil 209 } 210 211 func (d *dummyUI) ApproveTx(request *core.SignTxRequest) (core.SignTxResponse, error) { 212 d.calls = append(d.calls, "ApproveTx") 213 return core.SignTxResponse{}, core.ErrRequestDenied 214 } 215 216 func (d *dummyUI) ApproveSignData(request *core.SignDataRequest) (core.SignDataResponse, error) { 217 d.calls = append(d.calls, "ApproveSignData") 218 return core.SignDataResponse{}, core.ErrRequestDenied 219 } 220 221 func (d *dummyUI) ApproveListing(request *core.ListRequest) (core.ListResponse, error) { 222 d.calls = append(d.calls, "ApproveListing") 223 return core.ListResponse{}, core.ErrRequestDenied 224 } 225 226 func (d *dummyUI) ApproveNewAccount(request *core.NewAccountRequest) (core.NewAccountResponse, error) { 227 d.calls = append(d.calls, "ApproveNewAccount") 228 return core.NewAccountResponse{}, core.ErrRequestDenied 229 } 230 231 func (d *dummyUI) ShowError(message string) { 232 d.calls = append(d.calls, "ShowError") 233 } 234 235 func (d *dummyUI) ShowInfo(message string) { 236 d.calls = append(d.calls, "ShowInfo") 237 } 238 239 func (d *dummyUI) OnApprovedTx(tx ethapi.SignTransactionResult) { 240 d.calls = append(d.calls, "OnApprovedTx") 241 } 242 243 func (d *dummyUI) OnSignerStartup(info core.StartupInfo) { 244 } 245 246 //TestForwarding tests that the rule-engine correctly dispatches requests to the next caller 247 func TestForwarding(t *testing.T) { 248 249 js := "" 250 ui := &dummyUI{make([]string, 0)} 251 jsBackend := storage.NewEphemeralStorage() 252 r, err := NewRuleEvaluator(ui, jsBackend) 253 if err != nil { 254 t.Fatalf("Failed to create js engine: %v", err) 255 } 256 if err = r.Init(js); err != nil { 257 t.Fatalf("Failed to load bootstrap js: %v", err) 258 } 259 r.ApproveSignData(nil) 260 r.ApproveTx(nil) 261 r.ApproveNewAccount(nil) 262 r.ApproveListing(nil) 263 r.ShowError("test") 264 r.ShowInfo("test") 265 266 //This one is not forwarded 267 r.OnApprovedTx(ethapi.SignTransactionResult{}) 268 269 expCalls := 6 270 if len(ui.calls) != expCalls { 271 272 t.Errorf("Expected %d forwarded calls, got %d: %s", expCalls, len(ui.calls), strings.Join(ui.calls, ",")) 273 274 } 275 276 } 277 278 func TestMissingFunc(t *testing.T) { 279 r, err := initRuleEngine(JS) 280 if err != nil { 281 t.Errorf("Couldn't create evaluator %v", err) 282 return 283 } 284 285 _, err = r.execute("MissingMethod", "test") 286 287 if err == nil { 288 t.Error("Expected error") 289 } 290 291 approved, err := r.checkApproval("MissingMethod", nil, nil) 292 if err == nil { 293 t.Errorf("Expected missing method to yield error'") 294 } 295 if approved { 296 t.Errorf("Expected missing method to cause non-approval") 297 } 298 t.Logf("Err %v", err) 299 300 } 301 func TestStorage(t *testing.T) { 302 303 js := ` 304 function testStorage(){ 305 storage.put("mykey", "myvalue") 306 a = storage.get("mykey") 307 308 storage.put("mykey", ["a", "list"]) // Should result in "a,list" 309 a += storage.get("mykey") 310 311 312 storage.put("mykey", {"an": "object"}) // Should result in "[object Object]" 313 a += storage.get("mykey") 314 315 316 storage.put("mykey", JSON.stringify({"an": "object"})) // Should result in '{"an":"object"}' 317 a += storage.get("mykey") 318 319 a += storage.get("missingkey") //Missing keys should result in empty string 320 storage.put("","missing key==noop") // Can't store with 0-length key 321 a += storage.get("") // Should result in '' 322 323 var b = new BigNumber(2) 324 var c = new BigNumber(16)//"0xf0",16) 325 var d = b.plus(c) 326 console.log(d) 327 return a 328 } 329 ` 330 r, err := initRuleEngine(js) 331 if err != nil { 332 t.Errorf("Couldn't create evaluator %v", err) 333 return 334 } 335 336 v, err := r.execute("testStorage", nil) 337 338 if err != nil { 339 t.Errorf("Unexpected error %v", err) 340 } 341 retval := v.ToString().String() 342 343 if err != nil { 344 t.Errorf("Unexpected error %v", err) 345 } 346 exp := `myvaluea,list[object Object]{"an":"object"}` 347 if retval != exp { 348 t.Errorf("Unexpected data, expected '%v', got '%v'", exp, retval) 349 } 350 t.Logf("Err %v", err) 351 352 } 353 354 const ExampleTxWindow = ` 355 function big(str){ 356 if(str.slice(0,2) == "0x"){ return new BigNumber(str.slice(2),16)} 357 return new BigNumber(str) 358 } 359 360 // Time window: 1 week 361 var window = 1000* 3600*24*7; 362 363 // Limit : 1 ether 364 var limit = new BigNumber("1e18"); 365 366 function isLimitOk(transaction){ 367 var value = big(transaction.value) 368 // Start of our window function 369 var windowstart = new Date().getTime() - window; 370 371 var txs = []; 372 var stored = storage.get('txs'); 373 374 if(stored != ""){ 375 txs = JSON.parse(stored) 376 } 377 // First, remove all that have passed out of the time-window 378 var newtxs = txs.filter(function(tx){return tx.tstamp > windowstart}); 379 console.log(txs, newtxs.length); 380 381 // Secondly, aggregate the current sum 382 sum = new BigNumber(0) 383 384 sum = newtxs.reduce(function(agg, tx){ return big(tx.value).plus(agg)}, sum); 385 console.log("ApproveTx > Sum so far", sum); 386 console.log("ApproveTx > Requested", value.toNumber()); 387 388 // Would we exceed weekly limit ? 389 return sum.plus(value).lt(limit) 390 391 } 392 function ApproveTx(r){ 393 console.log(r) 394 console.log(typeof(r)) 395 if (isLimitOk(r.transaction)){ 396 return "Approve" 397 } 398 return "Nope" 399 } 400 401 /** 402 * OnApprovedTx(str) is called when a transaction has been approved and signed. The parameter 403 * 'response_str' contains the return value that will be sent to the external caller. 404 * The return value from this method is ignore - the reason for having this callback is to allow the 405 * ruleset to keep track of approved transactions. 406 * 407 * When implementing rate-limited rules, this callback should be used. 408 * If a rule responds with neither 'Approve' nor 'Reject' - the tx goes to manual processing. If the user 409 * then accepts the transaction, this method will be called. 410 * 411 * TLDR; Use this method to keep track of signed transactions, instead of using the data in ApproveTx. 412 */ 413 function OnApprovedTx(resp){ 414 var value = big(resp.tx.value) 415 var txs = [] 416 // Load stored transactions 417 var stored = storage.get('txs'); 418 if(stored != ""){ 419 txs = JSON.parse(stored) 420 } 421 // Add this to the storage 422 txs.push({tstamp: new Date().getTime(), value: value}); 423 storage.put("txs", JSON.stringify(txs)); 424 } 425 426 ` 427 428 func dummyTx(value hexutil.Big) *core.SignTxRequest { 429 to, _ := mixAddr("000000000000000000000000000000000000dead") 430 from, _ := mixAddr("000000000000000000000000000000000000dead") 431 n := hexutil.Uint64(3) 432 gas := hexutil.Uint64(21000) 433 gasPrice := hexutil.Big(*big.NewInt(2000000)) 434 435 return &core.SignTxRequest{ 436 Transaction: apitypes.SendTxArgs{ 437 From: *from, 438 To: to, 439 Value: value, 440 Nonce: n, 441 GasPrice: &gasPrice, 442 Gas: gas, 443 }, 444 Callinfo: []apitypes.ValidationInfo{ 445 {Typ: "Warning", Message: "All your base are bellong to us"}, 446 }, 447 Meta: core.Metadata{Remote: "remoteip", Local: "localip", Scheme: "inproc"}, 448 } 449 } 450 451 func dummyTxWithV(value uint64) *core.SignTxRequest { 452 v := big.NewInt(0).SetUint64(value) 453 h := hexutil.Big(*v) 454 return dummyTx(h) 455 } 456 457 func dummySigned(value *big.Int) *types.Transaction { 458 to := common.HexToAddress("000000000000000000000000000000000000dead") 459 gas := uint64(21000) 460 gasPrice := big.NewInt(2000000) 461 data := make([]byte, 0) 462 return types.NewTransaction(3, to, value, gas, gasPrice, data) 463 } 464 465 func TestLimitWindow(t *testing.T) { 466 r, err := initRuleEngine(ExampleTxWindow) 467 if err != nil { 468 t.Errorf("Couldn't create evaluator %v", err) 469 return 470 } 471 // 0.3 ether: 429D069189E0000 wei 472 v := big.NewInt(0).SetBytes(common.Hex2Bytes("0429D069189E0000")) 473 h := hexutil.Big(*v) 474 // The first three should succeed 475 for i := 0; i < 3; i++ { 476 unsigned := dummyTx(h) 477 resp, err := r.ApproveTx(unsigned) 478 if err != nil { 479 t.Errorf("Unexpected error %v", err) 480 } 481 if !resp.Approved { 482 t.Errorf("Expected check to resolve to 'Approve'") 483 } 484 // Create a dummy signed transaction 485 486 response := ethapi.SignTransactionResult{ 487 Tx: dummySigned(v), 488 Raw: common.Hex2Bytes("deadbeef"), 489 } 490 r.OnApprovedTx(response) 491 } 492 // Fourth should fail 493 resp, _ := r.ApproveTx(dummyTx(h)) 494 if resp.Approved { 495 t.Errorf("Expected check to resolve to 'Reject'") 496 } 497 } 498 499 // dontCallMe is used as a next-handler that does not want to be called - it invokes test failure 500 type dontCallMe struct { 501 t *testing.T 502 } 503 504 func (d *dontCallMe) OnInputRequired(info core.UserInputRequest) (core.UserInputResponse, error) { 505 d.t.Fatalf("Did not expect next-handler to be called") 506 return core.UserInputResponse{}, nil 507 } 508 509 func (d *dontCallMe) RegisterUIServer(api *core.UIServerAPI) { 510 } 511 512 func (d *dontCallMe) OnSignerStartup(info core.StartupInfo) { 513 } 514 515 func (d *dontCallMe) ApproveTx(request *core.SignTxRequest) (core.SignTxResponse, error) { 516 d.t.Fatalf("Did not expect next-handler to be called") 517 return core.SignTxResponse{}, core.ErrRequestDenied 518 } 519 520 func (d *dontCallMe) ApproveSignData(request *core.SignDataRequest) (core.SignDataResponse, error) { 521 d.t.Fatalf("Did not expect next-handler to be called") 522 return core.SignDataResponse{}, core.ErrRequestDenied 523 } 524 525 func (d *dontCallMe) ApproveListing(request *core.ListRequest) (core.ListResponse, error) { 526 d.t.Fatalf("Did not expect next-handler to be called") 527 return core.ListResponse{}, core.ErrRequestDenied 528 } 529 530 func (d *dontCallMe) ApproveNewAccount(request *core.NewAccountRequest) (core.NewAccountResponse, error) { 531 d.t.Fatalf("Did not expect next-handler to be called") 532 return core.NewAccountResponse{}, core.ErrRequestDenied 533 } 534 535 func (d *dontCallMe) ShowError(message string) { 536 d.t.Fatalf("Did not expect next-handler to be called") 537 } 538 539 func (d *dontCallMe) ShowInfo(message string) { 540 d.t.Fatalf("Did not expect next-handler to be called") 541 } 542 543 func (d *dontCallMe) OnApprovedTx(tx ethapi.SignTransactionResult) { 544 d.t.Fatalf("Did not expect next-handler to be called") 545 } 546 547 //TestContextIsCleared tests that the rule-engine does not retain variables over several requests. 548 // if it does, that would be bad since developers may rely on that to store data, 549 // instead of using the disk-based data storage 550 func TestContextIsCleared(t *testing.T) { 551 552 js := ` 553 function ApproveTx(){ 554 if (typeof foobar == 'undefined') { 555 foobar = "Approve" 556 } 557 console.log(foobar) 558 if (foobar == "Approve"){ 559 foobar = "Reject" 560 }else{ 561 foobar = "Approve" 562 } 563 return foobar 564 } 565 ` 566 ui := &dontCallMe{t} 567 r, err := NewRuleEvaluator(ui, storage.NewEphemeralStorage()) 568 if err != nil { 569 t.Fatalf("Failed to create js engine: %v", err) 570 } 571 if err = r.Init(js); err != nil { 572 t.Fatalf("Failed to load bootstrap js: %v", err) 573 } 574 tx := dummyTxWithV(0) 575 r1, _ := r.ApproveTx(tx) 576 r2, _ := r.ApproveTx(tx) 577 if r1.Approved != r2.Approved { 578 t.Errorf("Expected execution context to be cleared between executions") 579 } 580 } 581 582 func TestSignData(t *testing.T) { 583 584 js := `function ApproveListing(){ 585 return "Approve" 586 } 587 function ApproveSignData(r){ 588 if( r.address.toLowerCase() == "0x694267f14675d7e1b9494fd8d72fefe1755710fa") 589 { 590 if(r.messages[0].value.indexOf("bazonk") >= 0){ 591 return "Approve" 592 } 593 return "Reject" 594 } 595 // Otherwise goes to manual processing 596 }` 597 r, err := initRuleEngine(js) 598 if err != nil { 599 t.Errorf("Couldn't create evaluator %v", err) 600 return 601 } 602 message := "baz bazonk foo" 603 hash, rawdata := accounts.TextAndHash([]byte(message)) 604 addr, _ := mixAddr("0x694267f14675d7e1b9494fd8d72fefe1755710fa") 605 606 t.Logf("address %v %v\n", addr.String(), addr.Original()) 607 608 nvt := []*apitypes.NameValueType{ 609 { 610 Name: "message", 611 Typ: "text/plain", 612 Value: message, 613 }, 614 } 615 resp, err := r.ApproveSignData(&core.SignDataRequest{ 616 Address: *addr, 617 Messages: nvt, 618 Hash: hash, 619 Meta: core.Metadata{Remote: "remoteip", Local: "localip", Scheme: "inproc"}, 620 Rawdata: []byte(rawdata), 621 }) 622 if err != nil { 623 t.Fatalf("Unexpected error %v", err) 624 } 625 if !resp.Approved { 626 t.Fatalf("Expected approved") 627 } 628 }