| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- package api
- import (
- "fmt"
- "github.com/ethereum/go-ethereum/common"
- "github.com/ethereum/go-ethereum/common/hexutil"
- "github.com/ethereum/go-ethereum/core/types"
- "github.com/ethereum/go-ethereum/crypto"
- "math"
- "math/big"
- "reflect"
- "time"
- )
- func SignTransaction(nonce uint64, toAddressStr string, value *big.Int, gasLimit uint64, gasPrice *big.Int, data string, privateKeyHex string) (string, string, error) {
- toAddress := common.HexToAddress(toAddressStr)
- // 获取私钥对象
- privateKey, err := crypto.HexToECDSA(privateKeyHex)
- if err != nil {
- return "nil", "nil", err
- }
- // 创建一个 Signer 对象
- chainID := big.NewInt(1116) // 假设使用 Chain ID 为 1 的链
- signer := types.NewEIP155Signer(chainID)
- // 创建交易对象
- tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, []byte(data))
- // 对交易进行签名
- signedTx, err := types.SignTx(tx, signer, privateKey)
- if err != nil {
- return "nil", "nil", err
- }
- rawData, _ := signedTx.MarshalBinary()
- txNew := new(types.Transaction)
- txNew.UnmarshalBinary((rawData))
- return signedTx.Hash().Hex(), hexutil.Encode(rawData), nil
- }
- func PrintTime(args ...interface{}) {
- t := time.Now().Format("2006-01-02 15:04:05.000000")
- fmt.Print(t)
- for _, arg := range args {
- if f, ok := arg.(float64); ok {
- fmt.Printf(" %.6f", f)
- } else {
- fmt.Print(" ", arg)
- }
- }
- fmt.Println()
- }
- func SpeedTest(function interface{}, args ...interface{}) {
- // 打印函数名和参数
- PrintTime("functionName:", reflect.TypeOf(function).Name(), "args:", args)
- // 转换函数类型为可调用的函数
- fn := reflect.ValueOf(function)
- // 执行一次函数以确保正确性
- result := fn.Call(convertArgs(args))
- PrintTime("return:", result)
- // 初始化计时器和统计数据
- minTime := time.Duration(math.MaxInt64)
- maxTime := time.Duration(0)
- initTime := time.Now()
- count := 0
- // 循环执行函数并计算执行时间
- for time.Since(initTime) < time.Second {
- lastTime := time.Now()
- fn.Call(convertArgs(args))
- chaTime := time.Since(lastTime)
- // 更新最小和最大时间
- if chaTime < minTime {
- minTime = chaTime
- }
- if chaTime > maxTime {
- maxTime = chaTime
- }
- count++
- }
- // 打印统计结果
- PrintTime("avgTimes", count, "minTime", minTime.Seconds(), "maxTime", maxTime.Seconds())
- // SpeedTest(SignTransaction, nonce, toAddress, value, gasLimit, gasPrice, data, privateKeyHex)
- }
- func convertArgs(args []interface{}) []reflect.Value {
- values := make([]reflect.Value, len(args))
- for i, arg := range args {
- values[i] = reflect.ValueOf(arg)
- }
- return values
- }
|