api.go 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package api
  2. import (
  3. "fmt"
  4. "github.com/ethereum/go-ethereum/common"
  5. "github.com/ethereum/go-ethereum/common/hexutil"
  6. "github.com/ethereum/go-ethereum/core/types"
  7. "github.com/ethereum/go-ethereum/crypto"
  8. "math"
  9. "math/big"
  10. "reflect"
  11. "time"
  12. )
  13. func SignTransaction(nonce uint64, toAddressStr string, value *big.Int, gasLimit uint64, gasPrice *big.Int, data string, privateKeyHex string) (string, string, error) {
  14. toAddress := common.HexToAddress(toAddressStr)
  15. // 获取私钥对象
  16. privateKey, err := crypto.HexToECDSA(privateKeyHex)
  17. if err != nil {
  18. return "nil", "nil", err
  19. }
  20. // 创建一个 Signer 对象
  21. chainID := big.NewInt(1116) // 假设使用 Chain ID 为 1 的链
  22. signer := types.NewEIP155Signer(chainID)
  23. // 创建交易对象
  24. tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, []byte(data))
  25. // 对交易进行签名
  26. signedTx, err := types.SignTx(tx, signer, privateKey)
  27. if err != nil {
  28. return "nil", "nil", err
  29. }
  30. rawData, _ := signedTx.MarshalBinary()
  31. txNew := new(types.Transaction)
  32. txNew.UnmarshalBinary((rawData))
  33. return signedTx.Hash().Hex(), hexutil.Encode(rawData), nil
  34. }
  35. func PrintTime(args ...interface{}) {
  36. t := time.Now().Format("2006-01-02 15:04:05.000000")
  37. fmt.Print(t)
  38. for _, arg := range args {
  39. if f, ok := arg.(float64); ok {
  40. fmt.Printf(" %.6f", f)
  41. } else {
  42. fmt.Print(" ", arg)
  43. }
  44. }
  45. fmt.Println()
  46. }
  47. func SpeedTest(function interface{}, args ...interface{}) {
  48. // 打印函数名和参数
  49. PrintTime("functionName:", reflect.TypeOf(function).Name(), "args:", args)
  50. // 转换函数类型为可调用的函数
  51. fn := reflect.ValueOf(function)
  52. // 执行一次函数以确保正确性
  53. result := fn.Call(convertArgs(args))
  54. PrintTime("return:", result)
  55. // 初始化计时器和统计数据
  56. minTime := time.Duration(math.MaxInt64)
  57. maxTime := time.Duration(0)
  58. initTime := time.Now()
  59. count := 0
  60. // 循环执行函数并计算执行时间
  61. for time.Since(initTime) < time.Second {
  62. lastTime := time.Now()
  63. fn.Call(convertArgs(args))
  64. chaTime := time.Since(lastTime)
  65. // 更新最小和最大时间
  66. if chaTime < minTime {
  67. minTime = chaTime
  68. }
  69. if chaTime > maxTime {
  70. maxTime = chaTime
  71. }
  72. count++
  73. }
  74. // 打印统计结果
  75. PrintTime("avgTimes", count, "minTime", minTime.Seconds(), "maxTime", maxTime.Seconds())
  76. // SpeedTest(SignTransaction, nonce, toAddress, value, gasLimit, gasPrice, data, privateKeyHex)
  77. }
  78. func convertArgs(args []interface{}) []reflect.Value {
  79. values := make([]reflect.Value, len(args))
  80. for i, arg := range args {
  81. values[i] = reflect.ValueOf(arg)
  82. }
  83. return values
  84. }