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