github.com/amazechain/amc@v0.1.3/cmd/evmsdk/common.go (about) 1 // Copyright 2023 The AmazeChain Authors 2 // This file is part of the AmazeChain library. 3 // 4 // The AmazeChain 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 AmazeChain 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 AmazeChain library. If not, see <http://www.gnu.org/licenses/>. 16 17 package evmsdk 18 19 import ( 20 "context" 21 "crypto/ecdsa" 22 "crypto/rand" 23 "encoding/hex" 24 "encoding/json" 25 "errors" 26 "fmt" 27 "github.com/amazechain/amc/common/crypto" 28 "github.com/amazechain/amc/common/crypto/ecies" 29 "github.com/holiman/uint256" 30 "golang.org/x/crypto/sha3" 31 "io" 32 "io/ioutil" 33 "net/http" 34 "os" 35 "path" 36 "path/filepath" 37 "runtime" 38 "strconv" 39 "strings" 40 "sync" 41 "time" 42 43 commTyp "github.com/amazechain/amc/common/types" 44 "github.com/amazechain/amc/log" 45 "github.com/amazechain/amc/modules/state" 46 "github.com/go-kit/kit/transport/http/jsonrpc" 47 "github.com/gorilla/websocket" 48 49 "github.com/amazechain/amc/common/crypto/bls" 50 ) 51 52 const ( 53 VERSION = "" 54 EngineStateRunning = "running" 55 EngineStateStopped = "stopped" 56 57 RequestPath = "" 58 ConfigPath = "evm" 59 LogFile = "vertification_debug_log.txt" 60 ) 61 62 var ( 63 IS_DEBUG = true 64 ) 65 66 var EE *EvmEngine = &EvmEngine{} 67 68 func Emit(jsonText string) string { 69 defer func() { 70 if err := recover(); err != nil { 71 simpleLog("engine panic,err=%+v", err) 72 if err := EE.Stop(); err != nil { 73 simpleLog("engine stop error,err=%+v", err) 74 } 75 } 76 }() 77 er := new(EmitResponse) 78 eq := new(EmitRequest) 79 if err := json.Unmarshal([]byte(jsonText), eq); err != nil { 80 er.Code = 1 81 er.Message = err.Error() 82 return emitJSON(er) 83 } 84 85 if eq.Val != nil { 86 simpleLog("emit:", eq.Typ, eq.Val) 87 } else { 88 simpleLog("emit:", eq.Typ) 89 } 90 91 switch eq.Typ { 92 case "start": 93 if err := EE.Start(); err != nil { 94 er.Code, er.Message = 1, err.Error() 95 if innerErr, ok := err.(*InnerError); ok { 96 er.Code = innerErr.Code 97 er.Message = innerErr.Msg 98 } 99 return emitJSON(er) 100 } 101 case "stop": 102 if err := EE.Stop(); err != nil { 103 er.Code, er.Message = 1, err.Error() 104 return emitJSON(er) 105 } 106 case "setting": 107 if err := EE.Setting(eq); err != nil { 108 er.Code, er.Message = 1, err.Error() 109 return emitJSON(er) 110 } 111 case "list": 112 data, err := EE.List() 113 if err != nil { 114 er.Code, er.Message = 1, err.Error() 115 return emitJSON(er) 116 } 117 er.Data = data 118 case "blssign": 119 data, err := EE.BlsSign(eq.Val) 120 if err != nil { 121 er.Code, er.Message = 1, err.Error() 122 return emitJSON(er) 123 } 124 er.Data = data 125 case "blspubk": 126 data, err := EE.BlsPublicKey(eq.Val) 127 if err != nil { 128 er.Code, er.Message = 1, err.Error() 129 return emitJSON(er) 130 } 131 er.Data = data 132 case "state": 133 data := EE.State() 134 er.Data = data 135 case "decrypt": 136 data, err := EE.Decrypt(eq) 137 if err != nil { 138 er.Code, er.Message = 1, err.Error() 139 return emitJSON(er) 140 } 141 er.Data = data 142 case "encrypt": 143 data, err := EE.Encrypt(eq) 144 if err != nil { 145 er.Code, er.Message = 1, err.Error() 146 return emitJSON(er) 147 } 148 er.Data = data 149 case "test": 150 er.Message = Test() 151 } 152 153 return emitJSON(er) 154 } 155 156 func emitJSON(j interface{}) string { 157 a, _ := json.Marshal(j) 158 return string(a) 159 } 160 161 func (e *EvmEngine) initLogger(lvl string) { 162 IS_DEBUG = lvl == "debug" 163 if len(lvl) != 0 { 164 ensureLogFileExisted() 165 log.InitMobileLogger(filepath.Join(EE.AppBasePath, LogFile), IS_DEBUG) 166 } 167 } 168 169 func ensureLogFileExisted() { 170 logFilePath := path.Join(EE.AppBasePath, LogFile) 171 f, err := os.Open(logFilePath) 172 if err != nil { 173 f, err = os.Create(logFilePath) 174 if err != nil { 175 fmt.Printf("create log file error,err=%+v\n", err) 176 return 177 } 178 } 179 if err = f.Close(); err != nil { 180 fmt.Printf("log file close error,err=%+v", err) 181 } 182 } 183 184 func simpleLog(txt string, params ...interface{}) { 185 if IS_DEBUG { 186 ifces := make([]interface{}, 0, len(params)+1) 187 ifces = append(ifces, txt) 188 ifces = append(ifces, params...) 189 fmt.Println(ifces...) 190 log.Debug(txt, params...) 191 } 192 } 193 194 func simpleLogf(txt string, params ...interface{}) { 195 if IS_DEBUG { 196 fmt.Printf(txt+"\n", params...) 197 log.Debugf(txt, params...) 198 } 199 } 200 201 type Setting struct { 202 Height int 203 AppBasePath string 204 Account string 205 206 PrivKey string 207 } 208 209 type EmitRequest struct { 210 Typ string `json:"type"` 211 Val interface{} `json:"val"` 212 } 213 type EmitResponse struct { 214 Code int `json:"code"` 215 Message string `json:"message"` 216 Data interface{} `json:"data"` 217 } 218 219 type EvmEngine struct { 220 mu sync.Mutex `json:"-"` 221 ctx context.Context `json:"-"` 222 cancelFunc context.CancelFunc `json:"-"` 223 errChan chan []error `json:"-"` 224 225 Account string `json:"account"` 226 AppBasePath string `json:"app_base_path"` 227 EngineState string `json:"state"` 228 BlockChan chan string `json:"-"` 229 PrivKey string `json:"priv_key"` 230 ServerUri string `json:"server_uri"` 231 LogLevel string `json:"log_level"` 232 } 233 234 type AccountReward struct { 235 Account string 236 Number *uint256.Int 237 Value *uint256.Int 238 } 239 type AccountRewards []*AccountReward 240 241 func (r AccountRewards) Len() int { 242 return len(r) 243 } 244 245 func (r AccountRewards) Less(i, j int) bool { 246 return strings.Compare(r[i].Account, r[j].Account) > 0 247 } 248 249 func (r AccountRewards) Swap(i, j int) { 250 r[i], r[j] = r[j], r[i] 251 } 252 253 type InnerError struct { 254 Code int 255 Msg string 256 } 257 258 func (i InnerError) Error() string { return fmt.Sprintf("code:%+v,msg:%+v", i.Code, i.Msg) } 259 260 type AggSign struct { 261 Number uint64 `json:"number"` 262 StateRoot commTyp.Hash `json:"stateRoot"` 263 Sign commTyp.Signature `json:"sign"` 264 PublicKey commTyp.PublicKey `json:"publicKey"` 265 Address commTyp.Address `json:"address"` 266 } 267 268 func (e *EvmEngine) Start() error { 269 e.mu.Lock() 270 defer e.mu.Unlock() 271 e.ctx, e.cancelFunc = context.WithCancel(context.Background()) 272 if e.EngineState == EngineStateRunning { 273 return fmt.Errorf("evme is running") 274 } 275 e.EngineState = EngineStateRunning 276 277 if err := e.verificationTaskBg(); err != nil { 278 e.EngineState = EngineStateStopped 279 simpleLogf("launch verification task failed,err=%+v", err.Error()) 280 return err 281 } 282 return nil 283 } 284 285 func (e *EvmEngine) Stop() error { 286 e.mu.Lock() 287 e.EngineState = EngineStateStopped 288 if e.cancelFunc != nil { 289 e.cancelFunc() 290 } 291 if e.ctx != nil { 292 e.ctx.Done() 293 } 294 e.mu.Unlock() 295 return nil 296 } 297 298 func (e *EvmEngine) State() string { 299 e.mu.Lock() 300 defer e.mu.Unlock() 301 if e.EngineState == EngineStateRunning { 302 return "started" 303 } else { 304 return "stopped" 305 } 306 } 307 308 /* 309 { 310 "type":"setting", 311 "val":{ 312 "app_base_path":"/sd/0/evm/", 313 "account":"abcdef1234" 314 } 315 } 316 */ 317 func (e *EvmEngine) Setting(req *EmitRequest) error { 318 m, ok := req.Val.(map[string]interface{}) 319 if !ok { 320 return fmt.Errorf("type assert error,any==>smap") 321 } 322 323 appBasePath, ok := m["app_base_path"] 324 if ok { 325 if appBasePathStr, ok := appBasePath.(string); ok { 326 e.mu.Lock() 327 e.AppBasePath = appBasePathStr 328 e.mu.Unlock() 329 } 330 } 331 if privKeyIfce, ok := m["priv_key"]; ok { 332 if privKey, ok := privKeyIfce.(string); ok { 333 e.PrivKey = privKey 334 } 335 } 336 if serverUriIfce, ok := m["server_uri"]; ok { 337 if serverUri, ok := serverUriIfce.(string); ok { 338 e.ServerUri = serverUri 339 } 340 } 341 if accIfce, ok := m["account"]; ok { 342 if account, ok := accIfce.(string); ok { 343 e.Account = account 344 } 345 } 346 347 if logLvlIfce, ok := m["log_level"]; ok { 348 if loglvlStr, ok := logLvlIfce.(string); ok { 349 e.initLogger(loglvlStr) 350 } 351 } 352 353 return nil 354 } 355 func (e *EvmEngine) List() (interface{}, error) { 356 type l struct { 357 A string `json:"a"` 358 B bool `json:"b"` 359 C int `json:"c"` 360 } 361 362 ll := []*l{ 363 { 364 A: "a", 365 B: true, 366 C: 123, 367 }, { 368 A: "aa", 369 B: false, 370 C: 456, 371 }, 372 } 373 return ll, nil 374 } 375 func (e *EvmEngine) SaveFile() error { 376 return nil 377 } 378 func (e *EvmEngine) ReloadFile() error { 379 return nil 380 } 381 func (e *EvmEngine) BlsSign(req interface{}) (interface{}, error) { 382 var privKey, msg string 383 blsSignMap, ok := req.(map[string]interface{}) 384 if !ok { 385 return nil, errors.New("empty input value") 386 } 387 if privKeyIfce, ok := blsSignMap["priv_key"]; ok { 388 if privKey, ok = privKeyIfce.(string); !ok { 389 return nil, errors.New("priv_key type : array byte") 390 } 391 } else { 392 privKey = e.PrivKey 393 } 394 if msgIfce, ok := blsSignMap["msg"]; ok { 395 if msg, ok = msgIfce.(string); !ok { 396 return nil, errors.New("msg type : array byte") 397 } 398 } 399 return BlsSign(privKey, msg) 400 } 401 func (e *EvmEngine) BlsPublicKey(req interface{}) (interface{}, error) { 402 var privKey string 403 blsPublicKeyMap, ok := req.(map[string]interface{}) 404 if !ok { 405 return nil, errors.New("empty input value") 406 } 407 if privKeyIfce, ok := blsPublicKeyMap["priv_key"]; ok { 408 if privKey, ok = privKeyIfce.(string); !ok { 409 return nil, errors.New("priv_key type: array byte") 410 } 411 } else { 412 privKey = e.PrivKey 413 } 414 return BlsPublicKey(privKey) 415 } 416 417 func (e *EvmEngine) verificationTaskBg() error { 418 simpleLog("gen pubk") 419 pubk, err := BlsPublicKey(e.PrivKey) 420 if err != nil { 421 simpleLog("generate public key error,", err) 422 return err 423 } 424 simpleLog("init websocket") 425 wssvr, err := NewWebSocketService(e.ServerUri, e.Account) 426 if err != nil { 427 return err 428 } 429 simpleLog("init websocket chats") 430 ochan, ichan, err := wssvr.Chans(pubk.(string)) 431 if err != nil { 432 return err 433 } 434 go func() { 435 defer func() { 436 if err := recover(); err != nil { 437 buf := make([]byte, 4096) 438 runtime.Stack(buf, true) 439 simpleLog("vertification task down", "err", err) 440 simpleLog(string(buf)) 441 // simpleLogf("vertification task down,err=%+v,stk:%s:%d", err, f, l) 442 } 443 e.mu.Lock() 444 e.EngineState = EngineStateStopped 445 e.mu.Unlock() 446 }() 447 448 for { 449 select { 450 case <-e.ctx.Done(): 451 simpleLog("task has been cancelled") 452 return 453 case msg, ok := <-ochan: 454 if !ok { 455 simpleLog("task closed") 456 return 457 } 458 entire, err := e.unwrapJSONRPC(msg) 459 if err != nil { 460 simpleLog("unwrap jsonrpc message error,err=", err) 461 continue 462 } 463 resp, err := e.vertify(entire) 464 if err != nil { 465 simpleLog("ee verification failed", err) 466 continue 467 } 468 ichan <- resp 469 } 470 } 471 }() 472 return nil 473 } 474 475 func (e *EvmEngine) Decrypt(req *EmitRequest) (interface{}, error) { 476 477 var ( 478 params map[string]interface{} 479 privateKeyInterface interface{} 480 privateKeyString string 481 privateKey *ecdsa.PrivateKey 482 messageInterface interface{} 483 message string 484 messageBytes []byte 485 ok bool 486 err error 487 ) 488 489 if params, ok = req.Val.(map[string]interface{}); !ok { 490 return nil, fmt.Errorf("empty input value") 491 } 492 493 if privateKeyInterface, ok = params["priv_key"]; !ok { 494 return nil, fmt.Errorf("privateKey is empty") 495 } 496 497 if privateKeyString, ok = privateKeyInterface.(string); !ok { 498 return nil, fmt.Errorf("privateKey type is not string") 499 } 500 501 if privateKey, err = crypto.HexToECDSA(privateKeyString); err != nil { 502 return nil, fmt.Errorf("cannot decode private key") 503 } 504 505 if messageInterface, ok = params["msg"]; !ok { 506 return nil, fmt.Errorf("msg is empty") 507 } 508 if message, ok = messageInterface.(string); !ok { 509 return nil, fmt.Errorf("msg type is not string") 510 } 511 if messageBytes, err = hex.DecodeString(message); err != nil { 512 return nil, fmt.Errorf("msg cannote decode to bytes") 513 } 514 515 priKey := ecies.ImportECDSA(privateKey) 516 517 ms, err := priKey.Decrypt(messageBytes, nil, nil) 518 return hex.EncodeToString(ms), err 519 } 520 521 func (e *EvmEngine) Encrypt(req *EmitRequest) (interface{}, error) { 522 523 var ( 524 params map[string]interface{} 525 publicKeyInterface interface{} 526 publicKeyString string 527 publicKeyBytes []byte 528 publicKey *ecdsa.PublicKey 529 messageInterface interface{} 530 message string 531 messageBytes []byte 532 ok bool 533 err error 534 ) 535 536 if params, ok = req.Val.(map[string]interface{}); !ok { 537 return nil, fmt.Errorf("empty input value") 538 } 539 540 if publicKeyInterface, ok = params["public_key"]; !ok { 541 return nil, fmt.Errorf("public_key is empty") 542 } 543 544 if publicKeyString, ok = publicKeyInterface.(string); !ok { 545 return nil, fmt.Errorf("public_key type is not string") 546 } 547 548 if publicKeyBytes, err = hex.DecodeString(publicKeyString); err != nil { 549 return nil, fmt.Errorf("public_key cannote decode to bytes") 550 } 551 552 if publicKey, err = crypto.DecompressPubkey(publicKeyBytes); err != nil { 553 return nil, fmt.Errorf("cannot decode public key") 554 } 555 556 if messageInterface, ok = params["msg"]; !ok { 557 return nil, fmt.Errorf("msg is empty") 558 } 559 if message, ok = messageInterface.(string); !ok { 560 return nil, fmt.Errorf("msg type is not string") 561 } 562 563 if messageBytes, err = hex.DecodeString(message); err != nil { 564 return nil, fmt.Errorf("msg cannote decode to bytes") 565 } 566 567 pubKey := ecies.ImportECDSAPublic(publicKey) 568 ct, err := ecies.Encrypt(rand.Reader, pubKey, messageBytes, nil, nil) 569 570 return hex.EncodeToString(ct), err 571 } 572 573 //type innerEntireCode state.EntireCode 574 // 575 //func (h *innerEntireCode) UnmarshalJSON(in []byte) error { 576 // m := map[string]json.RawMessage{} 577 // if err := json.Unmarshal(in, &m); err != nil { 578 // return err 579 // } 580 // 581 // if err := json.Unmarshal(m["coinBase"], &h.CoinBase); err != nil { 582 // return err 583 // } 584 // if err := json.Unmarshal(m["codes"], &h.Codes); err != nil { 585 // return err 586 // } 587 // if rewardsBytes, ok := m["rewards"]; ok { 588 // m := []json.RawMessage{} 589 // if err := json.Unmarshal(rewardsBytes, &m); err == nil && len(m) != 0 { 590 // h.Rewards = make([]block.Reward, len(m)) 591 // for i, _ := range h.Rewards { 592 // rewardBean := block.Reward{ 593 // Amount: commTyp.NewInt64(0), 594 // } 595 // json.Unmarshal(m[i], &rewardBean) 596 // h.Rewards[i] = rewardBean 597 // } 598 // } 599 // } 600 // // if err := json.Unmarshal(m["rewards"], &h.Rewards); err != nil { 601 // // return err 602 // // } 603 // 604 // h.Entire.Header = &block.Header{ 605 // Difficulty: commTyp.NewInt64(0), 606 // Number: commTyp.NewInt64(0), 607 // BaseFee: commTyp.NewInt64(0), 608 // } 609 // if err := json.Unmarshal(m["entire"], &h.Entire); err != nil { 610 // return err 611 // } 612 // 613 // return nil 614 //} 615 616 func (e *EvmEngine) vertify(in []byte) ([]byte, error) { 617 var bean state.EntireCode 618 if err := json.Unmarshal(in, &bean); err != nil { 619 simpleLog("unmarshal vertify input error,err=", err) 620 return nil, err 621 } 622 623 if bean.Entire.Header == nil { 624 return nil, errors.New("nil pointer found") 625 } 626 // before state verify 627 var hash commTyp.Hash 628 hasher := sha3.NewLegacyKeccak256() 629 state.EncodeBeforeState(hasher, bean.Entire.Snap.Items, bean.Codes) 630 hasher.(crypto.KeccakState).Read(hash[:]) 631 if bean.Entire.Header.MixDigest != hash { 632 simpleLog("misMatch state hash", "want", bean.Entire.Header.MixDigest, "get", hash, "block", bean.Entire.Header.Number.Uint64()) 633 return nil, errors.New("state verify failed") 634 } 635 636 entirecode := state.EntireCode(bean) 637 stateRoot := verify(e.ctx, &entirecode) 638 639 res := AggSign{} 640 //stateroot 641 copy(res.StateRoot[:], stateRoot[:]) 642 if pubkIfce, err := BlsPublicKey(e.PrivKey); err == nil { 643 if pubkStr, ok := pubkIfce.(string); ok { 644 //publickey 645 copy(res.PublicKey[:], []byte(pubkStr)) 646 } 647 } 648 649 simpleLog("==calculated stateroot:", hex.EncodeToString(res.StateRoot[:])) 650 651 //privkey 652 res.Number = bean.Entire.Header.Number.Uint64() 653 privKeyBytes, err := hex.DecodeString(e.PrivKey) 654 if err != nil { 655 return nil, err 656 } 657 arr := [32]byte{} 658 copy(arr[:], privKeyBytes[:]) 659 sk, err := bls.SecretKeyFromRandom32Byte(arr) 660 if err != nil { 661 return nil, err 662 } 663 664 //sign 665 copy(res.Sign[:], sk.Sign(res.StateRoot[:]).Marshal()) 666 667 //address 668 res.Address = commTyp.HexToAddress(e.Account) 669 670 resBytes, err := json.Marshal(res) 671 if err != nil { 672 return nil, err 673 } 674 675 return resBytes, nil 676 } 677 678 func (e *EvmEngine) unwrapJSONRPC(in []byte) ([]byte, error) { 679 //"{\"jsonrpc\":\"2.0\",\"id\":1,\"error\":{\"code\":-32000,\"message\":\"unauthed address: 0xeB156a42dcaFcf155B07f3638892440C7dE5d564\"}}\n" 680 //ws consumer received msg:%!(EXTRA string=ws consumer received msg:, string={"jsonrpc":"2.0","id":1,"result":"0x96410b68a9f8875bb20fde06823eb861"} 681 req := new(jsonrpc.Request) 682 if err := json.Unmarshal(in, req); err != nil { 683 return nil, err 684 } 685 if len(req.Params) == 0 { 686 return []byte{}, errors.New("empty request params") 687 } 688 689 //type innerProtocolEntire struct { 690 // Entire json.RawMessage `json:"Entire"` 691 //} 692 type innerProtocol struct { 693 Subscription string `json:"subscription"` 694 Result json.RawMessage `json:"result"` 695 } 696 697 innerReq := new(innerProtocol) 698 if err := json.Unmarshal(req.Params, innerReq); err != nil { 699 return nil, err 700 } 701 702 return innerReq.Result, nil 703 } 704 705 //======test methods 706 707 func Test() string { 708 var sw strings.Builder 709 710 sw.WriteString("version:" + VERSION + "\r\n") 711 712 engJsonBytes, err := json.Marshal(EE) 713 if err == nil { 714 sw.WriteString(string(engJsonBytes) + "\r\n") 715 } 716 717 sw.WriteString("gettime:" + strconv.Itoa(int(GetTime())) + "\r\n") 718 719 sw.WriteString("getapppath:" + GetAppPath() + "\r\n") 720 721 sw.WriteString("getjson:" + GetJson() + "\r\n") 722 723 sw.WriteString("readfile_before:" + ReadTouchedFile() + "\r\n") 724 sw.WriteString("touchfile:" + TouchFile() + "\r\n") 725 sw.WriteString("readfile_after:" + ReadTouchedFile() + "\r\n") 726 727 ns := GetNetInfos() 728 sw.WriteString("getnetinfos:resplen:" + strconv.Itoa(len(ns)) + "\r\n") 729 730 sw.WriteString("backgroundthread:" + BackgroundLoop() + "\r\n") 731 732 sw.WriteString("bls tests " + BlsTest() + "\r\n") 733 734 //block here 735 sw.WriteString("wsocket:" + GetWebSocketConnect() + "\r\n") 736 737 return sw.String() 738 } 739 740 func GetTime() int64 { 741 return time.Now().Unix() 742 } 743 744 func GetAppPath() string { 745 path, err := os.Getwd() 746 if err != nil { 747 return err.Error() 748 } 749 750 return fmt.Sprintf("exec path:%+v;;setting_path:%+v", path, EE.AppBasePath) 751 } 752 753 func GetJson() string { 754 return `{ 755 "a":"b", 756 "c":"d" 757 }` 758 } 759 760 func TouchFile() string { 761 path := path.Join(EE.AppBasePath, "evm_touched_file.txt") 762 file, err := os.Create(path) 763 if err != nil { 764 return err.Error() 765 } 766 defer file.Close() 767 t := time.Now().Unix() 768 n, err := file.WriteString(strconv.Itoa(int(t)) + "|NAME=wux PWD=$WORK/src GOOS=android GOARCH=386 CC=$ANDROID_HOME/ndk/23.1.7779620/toolchains/llvm/prebuilt/linux-x86_64/bin/i686-linux-android21-clang CXX=$ANDROID_HOME/ndk/23.1.7779620/toolchains/llvm/prebuilt/linux-x86_64/bin/i686-linux-android21-clang++ CGO_ENABLED=1 GOPATH=$WORK:$GOPATH go mod tidy") 769 if err != nil { 770 return err.Error() 771 } 772 if n == 0 { 773 return "n==0" 774 } 775 return file.Name() 776 } 777 778 func ReadTouchedFile() string { 779 path := path.Join(EE.AppBasePath, "evm_touched_file.txt") 780 file, err := os.Open(path) 781 if err != nil { 782 return fmt.Sprintln("open touched file error,err=", err.Error()) 783 } 784 defer file.Close() 785 allBytes, err := io.ReadAll(file) 786 if err != nil { 787 return fmt.Sprintln("read touched file error,err=", err.Error()) 788 } 789 return string(allBytes) 790 } 791 792 func GetNetInfos() string { 793 resp, err := http.DefaultClient.Get("https://www.baidu.com") 794 if err != nil { 795 return err.Error() 796 } 797 htmlBytes, err := io.ReadAll(resp.Body) 798 if err != nil { 799 return err.Error() 800 } 801 return string(htmlBytes) 802 } 803 804 func RunLoop() string { 805 for { 806 <-time.After(2 * time.Second) 807 fmt.Println("1") 808 } 809 } 810 811 var backgroundLoopState = "" 812 813 func BackgroundLoop() string { 814 if len(backgroundLoopState) != 0 { 815 fmt.Println("BackgroundLoop running already") 816 return "BackgroundLoop running" 817 } 818 backgroundLoopState = "123" 819 go func() { 820 for { 821 <-time.After(2 * time.Second) 822 fmt.Println("alive") 823 } 824 }() 825 return "OK" 826 } 827 828 func GetWebSocketConnect() string { 829 var sw strings.Builder 830 conn, connResp, err := websocket.DefaultDialer.Dial("ws://54.175.247.94:20013", nil) 831 if err != nil { 832 return fmt.Sprintf("dial error,err=%+v \r\n", err) 833 } 834 defer conn.Close() 835 connRespBytes, err := ioutil.ReadAll(connResp.Body) 836 if err != nil { 837 return fmt.Sprintf("connresp return error,err=%+v", err) 838 } 839 sw.WriteString(string(connRespBytes)) 840 err = conn.WriteMessage(websocket.TextMessage, []byte(`{ 841 "jsonrpc":"2.0", 842 "method":"eth_subscribe", 843 "params":["newHeads"], 844 "id":1 845 }`)) 846 if err != nil { 847 return fmt.Sprintf("connresp write message error,err=%+v", err) 848 } 849 850 _, msg, err := conn.ReadMessage() 851 fmt.Println(string(msg)) 852 if err != nil { 853 sw.WriteString("read message error,err=" + err.Error()) 854 } 855 sw.WriteString("received message:" + string(msg)) 856 857 go func() { 858 innerConn, _, err := websocket.DefaultDialer.Dial("ws://174.129.114.74:8546", nil) 859 if err != nil { 860 fmt.Printf("bg dial error,err=%+v \r\n", err) 861 return 862 } 863 defer innerConn.Close() 864 err = innerConn.WriteMessage(websocket.TextMessage, []byte(`{ 865 "jsonrpc":"2.0", 866 "method":"eth_subscribe", 867 "params":["newHeads"], 868 "id":1 869 }`)) 870 if err != nil { 871 fmt.Printf("bg writemsg error,err=%+v \r\n", err) 872 return 873 } 874 for { 875 fmt.Println("bg readmsg:waitting") 876 _, msg, err := innerConn.ReadMessage() 877 if err != nil { 878 fmt.Println("bg readmsg error,err=" + err.Error()) 879 return 880 } 881 fmt.Println("bg readed msg:" + string(msg)) 882 } 883 }() 884 885 return sw.String() 886 } 887 888 func BlsTest() string { 889 var sw strings.Builder 890 891 var err error 892 err = bls.TestSignVerify2() 893 if err != nil { 894 sw.WriteString(err.Error() + "\r\n") 895 } 896 err = bls.TestAggregateVerify2() 897 if err != nil { 898 sw.WriteString(err.Error() + "\r\n") 899 } 900 err = bls.TestAggregateVerify_CompressedSignatures2() 901 if err != nil { 902 sw.WriteString(err.Error() + "\r\n") 903 } 904 err = bls.TestFastAggregateVerify2() 905 if err != nil { 906 sw.WriteString(err.Error() + "\r\n") 907 } 908 err = bls.TestVerifyCompressed2() 909 if err != nil { 910 sw.WriteString(err.Error() + "\r\n") 911 } 912 err = bls.TestMultipleSignatureVerification2() 913 if err != nil { 914 sw.WriteString(err.Error() + "\r\n") 915 } 916 err = bls.TestFastAggregateVerify_ReturnsFalseOnEmptyPubKeyList2() 917 if err != nil { 918 sw.WriteString(err.Error() + "\r\n") 919 } 920 err = bls.TestEth2FastAggregateVerify2() 921 if err != nil { 922 sw.WriteString(err.Error() + "\r\n") 923 } 924 err = bls.TestEth2FastAggregateVerify_ReturnsFalseOnEmptyPubKeyList2() 925 if err != nil { 926 sw.WriteString(err.Error() + "\r\n") 927 } 928 err = bls.TestEth2FastAggregateVerify_ReturnsTrueOnG2PointAtInfinity2() 929 if err != nil { 930 sw.WriteString(err.Error() + "\r\n") 931 } 932 err = bls.TestSignatureFromBytes2() 933 if err != nil { 934 sw.WriteString(err.Error() + "\r\n") 935 } 936 err = bls.TestMultipleSignatureFromBytes2() 937 if err != nil { 938 sw.WriteString(err.Error() + "\r\n") 939 } 940 err = bls.TestCopy2() 941 if err != nil { 942 sw.WriteString(err.Error() + "\r\n") 943 } 944 err = bls.TestSecretKeyFromBytes2() 945 if err != nil { 946 sw.WriteString(err.Error() + "\r\n") 947 } 948 949 sw.WriteString("bls test done.") 950 sw.WriteString("==============") 951 952 return sw.String() 953 }