Commit d4249455 authored by duanjinfei's avatar duanjinfei

change grpc bath sign tx

parent 077f0efa
......@@ -2,3 +2,4 @@
logs
root
cpuProfile.prof
*.DS_Store
\ No newline at end of file
......@@ -4,18 +4,23 @@ GOBIN = $(shell pwd)/build/bin
GO ?= latest
GOFILES_NOVENDOR := $(shell go list -f "{{.Dir}}" ./...)
default: metacryptor
default: metacryptor testclient
all: metacryptor metacryptor-ocl
all: metacryptor metacryptor-ocl testclient
metacryptor-ocl:
go build -tags opencl -o=${GOBIN}/$@
@echo "Done building."
metacryptor:
go build -o=${GOBIN}/$@
go build -o=${GOBIN}/$@ ./cmd/metacryptor
@echo "Done building."
testclient:
go build -o=${GOBIN}/$@ ./cmd/testclient
@echo "Done building."
clean:
rm -fr build/*
docker:
......
package main
import "runtime"
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
Execute()
}
package main
import (
"fmt"
"github.com/spf13/cobra"
)
var versionDetail bool
func init() {
RootCmd.AddCommand(versionCmd)
versionDetail = *versionCmd.Flags().BoolP("detail", "d", true, "Print detail version info")
}
// versionCmd represents the base command when called without any subcommands
var versionCmd = &cobra.Command{
Use: "version",
Short: "Print version number",
Long: ``,
Run: func(cmd *cobra.Command, args []string) {
if versionDetail {
fmt.Println("detail version:v1.0.0")
} else {
fmt.Println("version:v1.0.0")
}
},
}
package main
import (
"fmt"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/common/log"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/config"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/service"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/worker"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/xecc"
"github.com/fsnotify/fsnotify"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"google.golang.org/grpc"
"net"
"os"
"path"
"path/filepath"
"sync"
)
var cfgFile string
var Verbose bool
var routineCount uint
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "metacryptor",
Short: "The MetaCryptor command-line interface",
Long: ``,
Run: func(cmd *cobra.Command, args []string) {
runNode()
},
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
}
func Execute() {
if err := RootCmd.Execute(); err != nil {
log.Fatal(err)
os.Exit(-1)
}
}
func init() {
cobra.OnInitialize(initConfig)
RootCmd.PersistentFlags().UintVar(&routineCount, "routine", 2, "routine count for corrupt do task")
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "config.toml", "config file (default is ./config.yaml)")
RootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
log.InitLog()
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
viper.SetConfigName("config") // name of config file (without extension)
if cfgFile != "" { // enable ability to specify config file via flag
//log.Warn(">>> cfgFile: ", cfgFile)
viper.SetConfigFile(cfgFile)
configDir := path.Dir(cfgFile)
if configDir != "." && configDir != dir {
viper.AddConfigPath(configDir)
}
}
viper.AddConfigPath(".")
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
log.Info("Using config file:", viper.ConfigFileUsed())
} else {
log.Error("Read config failed", "error", err)
return
}
_, err = config.ParseConfig(viper.ConfigFileUsed())
if err != nil {
log.WithField("error", err).Fatal("parse config failed")
return
}
//log.Info("config is", config.GetConfig())
config.GetConfig().SetRoutineCount(routineCount)
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
log.Warn("Config file changed:", e.Name)
})
}
func runNode() {
xecc.XeccInstance()
wk := worker.NewWorker()
wk.Start()
lis, err := net.Listen("tcp", config.GetConfig().GpcAddress)
if err != nil {
fmt.Printf("failed to listen: %v", err)
return
}
s := grpc.NewServer()
service.RegisterCrypter(s, wk)
err = s.Serve(lis)
if err != nil {
fmt.Printf("failed to serve: %v", err)
return
}
wg := sync.WaitGroup{}
wg.Add(1)
wg.Wait()
}
package main
import (
"context"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/common"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/common/log"
basetype "github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/base/v1"
metacrypter "github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/crypter/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"math/big"
)
func main() {
client, err := grpc.Dial("127.0.0.1:38001", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Error("dial server failed", err)
}
accounts := common.CreateAccounts(1)
log.Info("account address is ", accounts[0].Address.String())
tmptx := accounts[0].MakeInitTx(big.NewInt(100))
crypterclient := metacrypter.NewCrypterServiceClient(client)
signTxReq := new(metacrypter.BatchSignTxRequest)
signTxReq.RawTx = make([]*basetype.MetaTxBase, 0)
{
var err error
stx := &basetype.MetaTxBase{
TxHash: common.ToHash(tmptx.Hash().Bytes()),
TxType: 1,
ChainId: common.FromBigInt(big.NewInt(100)),
Gas: tmptx.Gas(),
GasPrice: common.FromBigInt(tmptx.GasPrice()),
Value: common.FromBigInt(tmptx.Value()),
Data: tmptx.Data(),
Nonce: tmptx.Nonce(),
To: common.FromEthAddress(tmptx.To()),
}
signTxReq.RawTx = append(signTxReq.RawTx, stx)
signTxReq.Private = common.FromHex(accounts[0].Private)
signRes, err := crypterclient.BatchSignTx(context.Background(), signTxReq)
if err != nil {
log.Errorf("batch sign tx failed with error:(%s)", err)
return
}
recoverReq := new(metacrypter.BatchRecoverTxRequest)
recoverReq.RawTx = signRes.SignedTx
recoverRes, err := crypterclient.BatchRecoverTx(context.Background(), recoverReq, grpc.EmptyCallOption{})
if err != nil {
log.Error("batch recover batch signed tx failed", err)
} else {
log.Info("recover batch signed tx got from ", recoverRes.RecoverdTx[0].From)
}
}
{
req := new(metacrypter.BatchRecoverTxRequest)
req.RawTx = make([]*basetype.MetaTxBase, 0)
v, r, s := tmptx.RawSignatureValues()
log.WithField("txhash", tmptx.Hash().String()).Info("txhash")
log.WithField("r", common.Bytes2Hex(r.Bytes())).Info("tx r")
log.WithField("s", common.Bytes2Hex(s.Bytes())).Info("tx s")
log.WithField("v", common.Bytes2Hex(v.Bytes())).Info("tx v")
rtx := &basetype.MetaTxBase{
TxHash: common.ToHash(tmptx.Hash().Bytes()),
TxType: 1,
ChainId: common.FromBigInt(big.NewInt(100)),
Gas: tmptx.Gas(),
GasPrice: common.FromBigInt(tmptx.GasPrice()),
Value: common.FromBigInt(tmptx.Value()),
Data: tmptx.Data(),
Nonce: tmptx.Nonce(),
To: common.FromEthAddress(tmptx.To()),
R: common.FromBigInt(r),
S: common.FromBigInt(s),
V: common.FromBigInt(v),
}
req.RawTx = append(req.RawTx, rtx)
res, err := crypterclient.BatchRecoverTx(context.Background(), req, grpc.EmptyCallOption{})
if err != nil {
log.Error("batch recover tx failed", err)
}
log.Info("recover got from ", res.RecoverdTx[0].From)
}
}
package main
package common
import (
"crypto/ecdsa"
......@@ -33,7 +33,7 @@ func (acc *Account) MakeInitTx(chainid *big.Int) *types.Transaction {
return tx
}
func (acc *Account) SignTx(tx *types.Transaction, chainid *big.Int) (*types.Transaction, error){
func (acc *Account) SignTx(tx *types.Transaction, chainid *big.Int) (*types.Transaction, error) {
signedTx, err := types.SignTx(tx, types.NewEIP155Signer(chainid), acc.PK)
if err != nil {
return nil, err
......@@ -43,8 +43,8 @@ func (acc *Account) SignTx(tx *types.Transaction, chainid *big.Int) (*types.Tran
func CreateAccounts(count int) []*Account {
accs := make([]*Account, 0, count)
for i:=0; i < count; i++ {
pk,_ := crypto.GenerateKey()
for i := 0; i < count; i++ {
pk, _ := crypto.GenerateKey()
addr := crypto.PubkeyToAddress(pk.PublicKey)
private := hexutil.Encode(crypto.FromECDSA(pk))
accs = append(accs, &Account{Address: addr, Private: private, PK: pk})
......
......@@ -16,20 +16,14 @@ var (
type LogConfig struct {
Save uint `json:"save"`
Path string `json:"path"`
Level string `json:"level"`
}
func InitLog(logConfig LogConfig) {
func InitLog() {
mlog.Out = os.Stdout
var loglevel logrus.Level
err := loglevel.UnmarshalText([]byte(logConfig.Level))
if err != nil {
mlog.Panicf("set log level failed: %v", err)
}
mlog.SetLevel(loglevel)
mlog.SetLevel(logrus.InfoLevel)
mlog.Formatter = &logrus.TextFormatter{FullTimestamp: true, TimestampFormat: "2006-01-2 15:04:05.000"}
localFilesystemLogger(mlog, logConfig.Path, logConfig.Save)
//localFilesystemLogger(mlog, logConfig.Path, logConfig.Save)
}
func logWriter(logPath string, level string, save uint) *rotatelogs.RotateLogs {
......
grpc_addr = ":38002"
chain_id = 512512
\ No newline at end of file
package config
import (
"github.com/BurntSushi/toml"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/common/log"
"github.com/spf13/viper"
"io/ioutil"
"runtime"
)
type Config struct {
GpcAddress string `json:"grpc_addr" toml:"grpc_addr"`
ChainId int64 `json:"chain_id" toml:"chain_id"`
RootDir string
}
var _cfg *Config = nil
func (conf *Config) SetRoutineCount(n uint) {
viper.Set("routine_count", n)
}
func (conf *Config) GetRoutineCount() uint {
root := viper.GetUint("routine_count")
if root <= 0 {
root = uint(runtime.NumCPU())
}
return root
}
func ParseConfig(path string) (*Config, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
log.Error("get config failed", "err", err)
panic(err)
}
err = toml.Unmarshal(data, &_cfg)
//err = json.Unmarshal(data, &_cfg)
if err != nil {
log.Error("unmarshal config failed", "err", err)
panic(err)
}
return _cfg, nil
}
func GetConfig() *Config {
return _cfg
}
package crypto
import (
"github.com/CaduceusMetaverseProtocol/MetaCryptor/common"
basev1 "github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/base/v1"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"math/big"
)
func SignTx(pk []byte, tx *basev1.MetaTxBase, chainid *big.Int) error {
txdata := &types.LegacyTx{
Nonce: tx.Nonce,
GasPrice: common.ToBigInt(tx.GasPrice),
Gas: tx.Gas,
To: common.ToEthAddress(tx.To),
Value: common.ToBigInt(tx.Value),
Data: tx.Data,
}
ntx := types.NewTx(txdata)
signer := types.NewEIP155Signer(chainid)
privk, err := crypto.ToECDSA(pk)
if err != nil {
return err
}
signedTx, err := types.SignTx(ntx, signer, privk)
if err != nil {
return err
}
v, r, s := signedTx.RawSignatureValues()
tx.R = common.FromBigInt(r)
tx.S = common.FromBigInt(s)
tx.V = common.FromBigInt(v)
return nil
}
......@@ -3,34 +3,52 @@ module github.com/CaduceusMetaverseProtocol/MetaCryptor
go 1.18
require (
github.com/BurntSushi/toml v0.3.1
github.com/CaduceusMetaverseProtocol/MetaProtocol v0.0.1
github.com/CaduceusMetaverseProtocol/MetaTypes v1.0.0
github.com/btcsuite/btcd v0.21.0-beta
github.com/ethereum/go-ethereum v1.10.26
github.com/fsnotify/fsnotify v1.6.0
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible
github.com/rakyll/statik v0.1.7
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5
github.com/sirupsen/logrus v1.9.0
github.com/spf13/cobra v1.6.1
github.com/spf13/viper v1.15.0
github.com/tjfoc/gmsm v1.4.1
golang.org/x/crypto v0.5.0
google.golang.org/grpc v1.51.0
google.golang.org/grpc v1.52.0
)
require (
github.com/CaduceusMetaverseProtocol/MetaTypes v1.0.0 // indirect
github.com/btcsuite/btcd/btcec/v2 v2.2.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.0.1 // indirect
github.com/jonboulle/clockwork v0.3.0 // indirect
github.com/lestrrat-go/strftime v1.0.6 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/spf13/afero v1.9.3 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.4.2 // indirect
golang.org/x/net v0.5.0 // indirect
golang.org/x/sys v0.4.0 // indirect
golang.org/x/text v0.6.0 // indirect
google.golang.org/genproto v0.0.0-20221205194025-8222ab48f5fc // indirect
google.golang.org/genproto v0.0.0-20221227171554-f9683d7f8bef // indirect
google.golang.org/protobuf v1.28.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
replace github.com/CaduceusMetaverseProtocol/MetaProtocol => ../MetaProtocol-main
replace github.com/CaduceusMetaverseProtocol/MetaTypes => ../MetaTypes-main
replace github.com/ethereum/go-ethereum => github.com/CaduceusMetaverseProtocol/go-ethereum v1.10.26
This diff is collapsed.
package main
import (
"context"
"fmt"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/common"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/common/log"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/service"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/xecc"
basetype "github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/base/v1"
metacrypter "github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/crypter/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"math/big"
"net"
"time"
)
func test() {
time.Sleep(time.Second * 4)
client, err := grpc.Dial("127.0.0.1:38001", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Error("dial server failed", err)
}
accounts := CreateAccounts(1)
log.Info("account address is ", accounts[0].Address.String())
tx := accounts[0].MakeInitTx(big.NewInt(100))
crypterclient := metacrypter.NewCrypterServiceClient(client)
req := new(metacrypter.BatchRecoverTxRequest)
req.RawTx = make([]*basetype.MetaTxBase, 0)
v, r, s := tx.RawSignatureValues()
log.WithField("txhash", tx.Hash().String()).Info("txhash")
log.WithField("r", common.Bytes2Hex(r.Bytes())).Info("tx r")
log.WithField("s", common.Bytes2Hex(s.Bytes())).Info("tx s")
log.WithField("v", common.Bytes2Hex(v.Bytes())).Info("tx v")
rtx := &basetype.MetaTxBase{
TxHash: common.ToHash(tx.Hash().Bytes()),
TxType: 1,
ChainId: common.FromBigInt(big.NewInt(100)),
Gas: tx.Gas(),
GasPrice: common.FromBigInt(tx.GasPrice()),
Value: common.FromBigInt(tx.Value()),
Data: tx.Data(),
Nonce: tx.Nonce(),
To: common.FromEthAddress(tx.To()),
R: common.FromBigInt(r),
S: common.FromBigInt(s),
V: common.FromBigInt(v),
}
req.RawTx = append(req.RawTx, rtx)
res, err := crypterclient.BatchRecoverTx(context.Background(), req, grpc.EmptyCallOption{})
if err != nil {
log.Error("batch recover tx failed", err)
}
log.Info("recover got from ", res.RecoverdTx[0].From)
}
func main() {
xecc.XeccInstance()
lis, err := net.Listen("tcp", ":38001")
if err != nil {
fmt.Printf("failed to listen: %v", err)
return
}
s := grpc.NewServer()
service.RegisterCrypter(s)
go test()
err = s.Serve(lis)
if err != nil {
fmt.Printf("failed to serve: %v", err)
return
}
}
......@@ -2,74 +2,48 @@ package service
import (
"context"
"encoding/hex"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/common"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/common/log"
metatypes "github.com/CaduceusMetaverseProtocol/MetaTypes/types"
"math/big"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/crypto"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/worker"
metacrypter "github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/crypter/v1"
metatypes "github.com/CaduceusMetaverseProtocol/MetaTypes/types"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type CrypterServer struct {
worker *worker.Worker
metacrypter.UnimplementedCrypterServiceServer
}
func (*CrypterServer) BatchSign(ctx context.Context, req *metacrypter.BatchSignRequest) (*metacrypter.BatchSignResponse, error) {
func (s *CrypterServer) BatchSign(ctx context.Context, req *metacrypter.BatchSignRequest) (*metacrypter.BatchSignResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method BatchSign not implemented")
}
func (*CrypterServer) BatchVerify(ctx context.Context, req *metacrypter.BatchVerifyRequest) (*metacrypter.BatchVerifyResponse, error) {
func (s *CrypterServer) BatchVerify(ctx context.Context, req *metacrypter.BatchVerifyRequest) (*metacrypter.BatchVerifyResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method BatchVerify not implemented")
}
func (*CrypterServer) BatchRecover(ctx context.Context, req *metacrypter.BatchRecoverRequest) (*metacrypter.BatchRecoverResponse, error) {
func (s *CrypterServer) BatchRecover(ctx context.Context, req *metacrypter.BatchRecoverRequest) (*metacrypter.BatchRecoverResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method BatchRecover not implemented")
}
func (*CrypterServer) BatchRecoverTx(ctx context.Context, req *metacrypter.BatchRecoverTxRequest) (*metacrypter.BatchRecoverTxResponse, error) {
func (s *CrypterServer) BatchSignTx(ctx context.Context, req *metacrypter.BatchSignTxRequest) (*metacrypter.BatchSignTxResponse, error) {
log.Info("server get batch recover tx request")
signedTxs := s.worker.BatchSignTx(req.RawTx, req.Private)
response := new(metacrypter.BatchSignTxResponse)
response.SignedTx = signedTxs
return response, nil
}
func (s *CrypterServer) BatchRecoverTx(ctx context.Context, req *metacrypter.BatchRecoverTxRequest) (*metacrypter.BatchRecoverTxResponse, error) {
//tasks := make([]*XTaskSecp256k1RPubkey, len(req.RawTx))
//big8 := big.NewInt(8)
log.Info("server get batch recover tx request")
froms := make([][]byte, len(req.RawTx))
for i, tx := range req.RawTx {
log.WithField("txhash", tx.TxHash.String()).Info("txhash")
log.WithField("r", tx.R.String()).Info("tx r")
log.WithField("s", tx.S.String()).Info("tx s")
log.WithField("v", tx.V.String()).Info("tx v")
log.WithField("chainid", tx.ChainId.String()).Info("tx chainid")
froms := s.worker.BatchRecoverTx(req.RawTx)
V := common.ToBigInt(tx.V)
chainid := common.ToBigInt(tx.ChainId)
chainIdMul := new(big.Int).Mul(chainid, big.NewInt(2))
v := new(big.Int).Sub(V, chainIdMul)
vb := byte(v.Uint64() - 35)
log.WithField("vb is ", vb).Info("vb")
signature := make([]byte, 65)
copy(signature[:32], common.LeftPadBytes(tx.R.Bytes(), 32))
copy(signature[32:64], common.LeftPadBytes(tx.S.Bytes(), 32))
signature[64] = vb
pubk, err := crypto.RecoverPubkey(common.LeftPadBytes(crypto.SignedHash(tx, chainid), 32), signature)
if err != nil {
log.Info("recover failed for tx", "index", i, "err", err)
} else {
froms[i] = common.CopyBytes(crypto.Keccak256(pubk[1:])[12:])
log.Info("recover address is ", hex.EncodeToString(froms[i]))
}
//task := &XTaskSecp256k1RPubkey{
// Msg: tx.TxHash.Hash,
// Rsig: crypto.BytesCombine(common.LeftPadBytes(tx.R.Data, 32), common.LeftPadBytes(tx.S.Data, 32), []byte{vb}),
//}
//tasks[i] = task
}
response := new(metacrypter.BatchRecoverTxResponse)
response.RecoverdTx = req.RawTx
//resps, err := xecc.XeccInstance().BatchSecp256k1RecoverPubkey(tasks)
//if err != nil {
// return response, err
//}
for i := 0; i < len(response.RecoverdTx); i++ {
a := metatypes.BytesToAddress(froms[i])
......@@ -79,6 +53,6 @@ func (*CrypterServer) BatchRecoverTx(ctx context.Context, req *metacrypter.Batch
return response, nil
}
func RegisterCrypter(server *grpc.Server) {
metacrypter.RegisterCrypterServiceServer(server, &CrypterServer{})
func RegisterCrypter(server *grpc.Server, worker *worker.Worker) {
metacrypter.RegisterCrypterServiceServer(server, &CrypterServer{worker: worker})
}
package worker
import (
"errors"
"sync"
)
var (
ErrTaskPoolIsFull = errors.New("task pool is full")
)
type TaskHandle func(interface{})
type Tasks struct {
tasknum uint
handler TaskHandle
taskpool chan interface{}
wg sync.WaitGroup
}
func NewTasks(routine uint, handle TaskHandle) *Tasks {
return &Tasks{
tasknum: routine,
handler: handle,
taskpool: make(chan interface{}, 1000000),
}
}
func (t *Tasks) AddTask(task interface{}) error {
select {
case t.taskpool <- task:
return nil
default:
return ErrTaskPoolIsFull
}
}
func (t *Tasks) Stop() {
close(t.taskpool)
}
func (t *Tasks) Run() {
for i := uint(0); i < t.tasknum; i++ {
t.wg.Add(1)
go func() {
defer t.wg.Done()
for {
select {
case task, ok := <-t.taskpool:
if !ok {
return
}
t.handler(task)
}
}
}()
}
}
func (t *Tasks) Done() {
t.wg.Wait()
}
package worker
import (
"github.com/CaduceusMetaverseProtocol/MetaCryptor/common"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/common/log"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/config"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/crypto"
basev1 "github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/base/v1"
"math/big"
"sync"
)
type Worker struct {
recoverTask *Tasks
signTask *Tasks
}
func NewWorker() *Worker {
w := new(Worker)
w.recoverTask = NewTasks(config.GetConfig().GetRoutineCount(), w.handleRecoverTx)
w.signTask = NewTasks(config.GetConfig().GetRoutineCount(), w.handleSignTx)
return w
}
func (w *Worker) handleRecoverTx(t interface{}) {
defChainId := big.NewInt(config.GetConfig().ChainId)
item, ok := t.(*ItemRecover)
if !ok {
return
}
tx := item.tx
log.WithField("txHash", tx.TxHash.String()).Info("txHash")
log.WithField("r", tx.R.String()).Info("tx r")
log.WithField("s", tx.S.String()).Info("tx s")
log.WithField("v", tx.V.String()).Info("tx v")
log.WithField("chainId", tx.ChainId.String()).Info("tx chainId")
var chainid *big.Int
if tx.ChainId == nil {
chainid = defChainId
} else {
chainid = common.ToBigInt(tx.ChainId)
}
V := common.ToBigInt(tx.V)
chainIdMul := new(big.Int).Mul(chainid, big.NewInt(2))
v := new(big.Int).Sub(V, chainIdMul)
vb := byte(v.Uint64() - 35)
signature := make([]byte, 65)
copy(signature[:32], common.LeftPadBytes(tx.R.Bytes(), 32))
copy(signature[32:64], common.LeftPadBytes(tx.S.Bytes(), 32))
signature[64] = vb
pubk, err := crypto.RecoverPubkey(common.LeftPadBytes(crypto.SignedHash(tx, chainid), 32), signature)
if err != nil {
item.response <- err
} else {
item.response <- common.CopyBytes(crypto.Keccak256(pubk[1:])[12:])
}
}
func (w *Worker) handleSignTx(t interface{}) {
defChainId := big.NewInt(config.GetConfig().ChainId)
item := t.(*ItemSignTx)
tx := item.tx
var chainid *big.Int
if tx.ChainId == nil {
chainid = defChainId
} else {
chainid = common.ToBigInt(tx.ChainId)
}
err := crypto.SignTx(item.pk, tx, chainid)
if err != nil {
item.response <- err
} else {
item.response <- tx
}
}
func (w *Worker) Start() {
w.recoverTask.Run()
w.signTask.Run()
}
type ItemRecover struct {
tx *basev1.MetaTxBase
response chan interface{}
}
type ItemSignTx struct {
tx *basev1.MetaTxBase
pk []byte
response chan interface{}
}
func (w *Worker) BatchRecoverTx(txs []*basev1.MetaTxBase) [][]byte {
results := make([][]byte, len(txs))
wg := sync.WaitGroup{}
for i, tx := range txs {
wg.Add(1)
go func(tx *basev1.MetaTxBase, froms [][]byte, index int) {
defer wg.Done()
res := make(chan interface{})
if err := w.recoverTask.AddTask(&ItemRecover{tx: tx, response: res}); err != nil {
res <- err
}
data := <-res
switch msg := (data).(type) {
case error:
froms[index] = []byte{}
case []byte:
froms[index] = common.CopyBytes(msg)
}
}(tx, results, i)
}
wg.Wait()
return results
}
func (w *Worker) BatchSignTx(txs []*basev1.MetaTxBase, pk []byte) []*basev1.MetaTxBase {
results := make([]*basev1.MetaTxBase, len(txs))
wg := sync.WaitGroup{}
for i, tx := range txs {
wg.Add(1)
go func(tx *basev1.MetaTxBase, signedTxs []*basev1.MetaTxBase, index int) {
defer wg.Done()
res := make(chan interface{})
if err := w.signTask.AddTask(&ItemSignTx{pk: pk, tx: tx, response: res}); err != nil {
res <- err
}
data := <-res
switch msg := (data).(type) {
case error:
//froms[index] = []byte{}
case *basev1.MetaTxBase:
signedTxs[index] = msg
}
}(tx, results, i)
}
wg.Wait()
return results
}
......@@ -38,6 +38,14 @@ message BatchRecoverResponse {
repeated bytes pubkey = 1;
}
message BatchSignTxRequest {
repeated base.v1.MetaTxBase raw_tx = 1;
bytes private = 2;
}
message BatchSignTxResponse {
repeated base.v1.MetaTxBase signed_tx = 1;
}
message BatchRecoverTxRequest {
repeated base.v1.MetaTxBase raw_tx = 1;
}
......
......@@ -8,5 +8,6 @@ service CrypterService {
rpc BatchSign(BatchSignRequest) returns (BatchSignResponse) {}
rpc BatchVerify(BatchVerifyRequest) returns (BatchVerifyResponse) {}
rpc BatchRecover(BatchRecoverRequest) returns (BatchRecoverResponse) {}
rpc BatchSignTx(BatchSignTxRequest) returns (BatchSignTxResponse) {}
rpc BatchRecoverTx(BatchRecoverTxRequest) returns (BatchRecoverTxResponse) {}
}
......@@ -23,25 +23,26 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
func init() { proto.RegisterFile("crypter/v1/service.proto", fileDescriptor_05ac8b6606ffe814) }
var fileDescriptor_05ac8b6606ffe814 = []byte{
// 317 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x91, 0x4f, 0x4a, 0xc3, 0x40,
0x14, 0xc6, 0x6d, 0x04, 0xc1, 0x69, 0xe9, 0x62, 0x16, 0x22, 0xc5, 0x7f, 0xed, 0x01, 0x66, 0x18,
// 331 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0x4f, 0x4a, 0xc3, 0x40,
0x14, 0x87, 0x6d, 0x0a, 0x82, 0xd3, 0xd2, 0xc5, 0x2c, 0x44, 0x8a, 0xff, 0xda, 0x03, 0x64, 0x18,
0xdd, 0xd5, 0x5d, 0xba, 0x10, 0x04, 0x21, 0x34, 0x25, 0x54, 0x29, 0x48, 0x3a, 0x7d, 0xa6, 0x01,
0xdb, 0xa9, 0x33, 0x93, 0xa1, 0xbd, 0x8e, 0x4b, 0xcf, 0xe0, 0x09, 0x3c, 0x84, 0x0b, 0x97, 0x9e,
0x42, 0x9a, 0x99, 0xa4, 0x81, 0x12, 0x77, 0x79, 0xef, 0xfb, 0xcd, 0xef, 0x41, 0x3e, 0x74, 0xca,
0xe5, 0x66, 0xa5, 0x41, 0x52, 0xc3, 0xa8, 0x02, 0x69, 0x52, 0x0e, 0x64, 0x25, 0x85, 0x16, 0x18,
0xb9, 0x84, 0x18, 0xd6, 0xe9, 0x56, 0x28, 0x09, 0x6f, 0x19, 0x28, 0xfd, 0x2c, 0x41, 0xad, 0xc4,
0x52, 0x39, 0xfc, 0xfa, 0xdb, 0x43, 0xed, 0x81, 0xa5, 0x42, 0xeb, 0xc1, 0xf7, 0xe8, 0xd8, 0x8f,
0x35, 0x9f, 0x87, 0x69, 0xb2, 0xc4, 0x67, 0x64, 0xe7, 0x23, 0xe5, 0x7a, 0x68, 0x65, 0x9d, 0xf3,
0x9a, 0xd4, 0x9e, 0xe8, 0x1d, 0xe0, 0x00, 0x35, 0xf3, 0x75, 0x04, 0x32, 0x7d, 0xd9, 0xe0, 0x8b,
0x3d, 0xde, 0x06, 0x85, 0xef, 0xb2, 0x36, 0x2f, 0x8d, 0x21, 0x6a, 0xe5, 0xc1, 0x10, 0xb8, 0x30,
0x20, 0xf1, 0xfe, 0x13, 0x97, 0x14, 0xce, 0xab, 0x7a, 0xa0, 0x94, 0x3e, 0xa2, 0x76, 0x35, 0x19,
0xad, 0x71, 0xb7, 0xee, 0xd5, 0x68, 0x5d, 0x88, 0x7b, 0xff, 0x21, 0x85, 0xda, 0xff, 0x6c, 0xa0,
0x36, 0x17, 0x8b, 0x0a, 0xeb, 0xb7, 0xdc, 0x9f, 0x0e, 0xb6, 0x0d, 0x04, 0x8d, 0xa7, 0x30, 0x49,
0xf5, 0x3c, 0x9b, 0x12, 0x2e, 0x16, 0x74, 0x10, 0xcf, 0x32, 0x0e, 0x99, 0x7a, 0x00, 0x1d, 0x1b,
0x90, 0xca, 0x42, 0x5c, 0xbc, 0xd2, 0xed, 0xa6, 0x1c, 0x12, 0x58, 0xd2, 0xbc, 0x40, 0x9a, 0x08,
0xba, 0x6b, 0xf9, 0xd6, 0x7d, 0x1a, 0xf6, 0xee, 0x1d, 0x0e, 0xc6, 0xe3, 0x0f, 0x0f, 0xb9, 0x72,
0x49, 0xc4, 0xbe, 0xca, 0x61, 0x12, 0xb1, 0x1f, 0xef, 0x64, 0x37, 0x4c, 0xee, 0x02, 0x7f, 0xab,
0x9f, 0xc5, 0x3a, 0xfe, 0xf5, 0x9a, 0x2e, 0xe8, 0xf7, 0x23, 0x36, 0x3d, 0xca, 0xaf, 0xdc, 0xfc,
0x05, 0x00, 0x00, 0xff, 0xff, 0xbc, 0x94, 0xc4, 0x24, 0x71, 0x02, 0x00, 0x00,
0xdb, 0xa9, 0x33, 0x93, 0xa1, 0xbd, 0x8e, 0x4b, 0x57, 0x1e, 0xc0, 0x13, 0x78, 0x0c, 0x97, 0x9e,
0x42, 0x92, 0x99, 0x24, 0x85, 0x1a, 0x77, 0x79, 0xef, 0xfb, 0xe5, 0x7b, 0x0f, 0xe6, 0xa1, 0x13,
0x26, 0xb6, 0x6b, 0x05, 0x82, 0x68, 0x4a, 0x24, 0x08, 0x9d, 0x30, 0x70, 0xd7, 0x82, 0x2b, 0x8e,
0x91, 0x25, 0xae, 0xa6, 0xdd, 0xde, 0x4e, 0x4a, 0xc0, 0x6b, 0x0a, 0x52, 0x3d, 0x09, 0x90, 0x6b,
0xbe, 0x92, 0x36, 0x7e, 0xf5, 0xd1, 0x44, 0x9d, 0xa1, 0x49, 0x05, 0xc6, 0x83, 0xef, 0xd0, 0x91,
0x17, 0x29, 0xb6, 0x08, 0x92, 0x78, 0x85, 0x4f, 0xdd, 0xca, 0xe7, 0x96, 0xed, 0x91, 0x91, 0x75,
0xcf, 0x6a, 0xa8, 0x19, 0xd1, 0x3f, 0xc0, 0x3e, 0x6a, 0xe5, 0xed, 0x10, 0x44, 0xf2, 0xbc, 0xc5,
0xe7, 0x7b, 0x79, 0x03, 0x0a, 0xdf, 0x45, 0x2d, 0x2f, 0x8d, 0x01, 0x6a, 0xe7, 0x60, 0x04, 0x8c,
0x6b, 0x10, 0x78, 0xff, 0x17, 0x4b, 0x0a, 0xe7, 0x65, 0x7d, 0x60, 0x6f, 0xcd, 0x6c, 0xfb, 0xf1,
0xe6, 0x8f, 0x35, 0x0d, 0xa8, 0x5f, 0xb3, 0xe0, 0xa5, 0xf1, 0x01, 0x75, 0x76, 0x67, 0x8d, 0x37,
0xb8, 0x57, 0xb7, 0x47, 0xe5, 0xed, 0xff, 0x17, 0x29, 0xd4, 0xde, 0x67, 0x03, 0x75, 0x18, 0x5f,
0xee, 0x64, 0xbd, 0xb6, 0x7d, 0x3b, 0x3f, 0x7b, 0x53, 0xbf, 0xf1, 0x18, 0xc4, 0x89, 0x5a, 0xa4,
0x33, 0x97, 0xf1, 0x25, 0x19, 0x46, 0xf3, 0x94, 0x41, 0x2a, 0xef, 0x41, 0x45, 0x1a, 0x84, 0x34,
0x21, 0xc6, 0x5f, 0x48, 0xd6, 0x29, 0x8b, 0x18, 0x56, 0x24, 0x3f, 0x09, 0x12, 0x73, 0x52, 0xdd,
0xcd, 0x8d, 0xfd, 0xd4, 0xf4, 0xcd, 0x69, 0x0e, 0x27, 0x93, 0x77, 0x07, 0xd9, 0x73, 0x71, 0x43,
0xfa, 0x55, 0x16, 0xd3, 0x90, 0x7e, 0x3b, 0xc7, 0x55, 0x31, 0xbd, 0xf5, 0xbd, 0x4c, 0x3f, 0x8f,
0x54, 0xf4, 0xe3, 0xb4, 0x2c, 0x18, 0x0c, 0x42, 0x3a, 0x3b, 0xcc, 0xa7, 0x5c, 0xff, 0x06, 0x00,
0x00, 0xff, 0xff, 0x0a, 0xf6, 0xf3, 0x8c, 0xc3, 0x02, 0x00, 0x00,
}
......@@ -25,6 +25,7 @@ type CrypterServiceClient interface {
BatchSign(ctx context.Context, in *BatchSignRequest, opts ...grpc.CallOption) (*BatchSignResponse, error)
BatchVerify(ctx context.Context, in *BatchVerifyRequest, opts ...grpc.CallOption) (*BatchVerifyResponse, error)
BatchRecover(ctx context.Context, in *BatchRecoverRequest, opts ...grpc.CallOption) (*BatchRecoverResponse, error)
BatchSignTx(ctx context.Context, in *BatchSignTxRequest, opts ...grpc.CallOption) (*BatchSignTxResponse, error)
BatchRecoverTx(ctx context.Context, in *BatchRecoverTxRequest, opts ...grpc.CallOption) (*BatchRecoverTxResponse, error)
}
......@@ -63,6 +64,15 @@ func (c *crypterServiceClient) BatchRecover(ctx context.Context, in *BatchRecove
return out, nil
}
func (c *crypterServiceClient) BatchSignTx(ctx context.Context, in *BatchSignTxRequest, opts ...grpc.CallOption) (*BatchSignTxResponse, error) {
out := new(BatchSignTxResponse)
err := c.cc.Invoke(ctx, "/crypter.v1.CrypterService/BatchSignTx", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *crypterServiceClient) BatchRecoverTx(ctx context.Context, in *BatchRecoverTxRequest, opts ...grpc.CallOption) (*BatchRecoverTxResponse, error) {
out := new(BatchRecoverTxResponse)
err := c.cc.Invoke(ctx, "/crypter.v1.CrypterService/BatchRecoverTx", in, out, opts...)
......@@ -79,6 +89,7 @@ type CrypterServiceServer interface {
BatchSign(context.Context, *BatchSignRequest) (*BatchSignResponse, error)
BatchVerify(context.Context, *BatchVerifyRequest) (*BatchVerifyResponse, error)
BatchRecover(context.Context, *BatchRecoverRequest) (*BatchRecoverResponse, error)
BatchSignTx(context.Context, *BatchSignTxRequest) (*BatchSignTxResponse, error)
BatchRecoverTx(context.Context, *BatchRecoverTxRequest) (*BatchRecoverTxResponse, error)
mustEmbedUnimplementedCrypterServiceServer()
}
......@@ -96,6 +107,9 @@ func (UnimplementedCrypterServiceServer) BatchVerify(context.Context, *BatchVeri
func (UnimplementedCrypterServiceServer) BatchRecover(context.Context, *BatchRecoverRequest) (*BatchRecoverResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method BatchRecover not implemented")
}
func (UnimplementedCrypterServiceServer) BatchSignTx(context.Context, *BatchSignTxRequest) (*BatchSignTxResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method BatchSignTx not implemented")
}
func (UnimplementedCrypterServiceServer) BatchRecoverTx(context.Context, *BatchRecoverTxRequest) (*BatchRecoverTxResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method BatchRecoverTx not implemented")
}
......@@ -166,6 +180,24 @@ func _CrypterService_BatchRecover_Handler(srv interface{}, ctx context.Context,
return interceptor(ctx, in, info, handler)
}
func _CrypterService_BatchSignTx_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(BatchSignTxRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CrypterServiceServer).BatchSignTx(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/crypter.v1.CrypterService/BatchSignTx",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CrypterServiceServer).BatchSignTx(ctx, req.(*BatchSignTxRequest))
}
return interceptor(ctx, in, info, handler)
}
func _CrypterService_BatchRecoverTx_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(BatchRecoverTxRequest)
if err := dec(in); err != nil {
......@@ -203,6 +235,10 @@ var CrypterService_ServiceDesc = grpc.ServiceDesc{
MethodName: "BatchRecover",
Handler: _CrypterService_BatchRecover_Handler,
},
{
MethodName: "BatchSignTx",
Handler: _CrypterService_BatchSignTx_Handler,
},
{
MethodName: "BatchRecoverTx",
Handler: _CrypterService_BatchRecoverTx_Handler,
......
......@@ -24,9 +24,11 @@ const _ = grpc.SupportPackageIsVersion7
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type RingServiceClient interface {
Ping(ctx context.Context, in *RequestPing, opts ...grpc.CallOption) (*ResponsePing, error)
// rpc BroadcastTx(RequestBroadcastTx) returns (ResponseBroadcastTx);
//rpc BroadcastTx(RequestBroadcastTx) returns (ResponseBroadcastTx);
BroadcastTxs(ctx context.Context, in *BroadcastEthTxWithFromRequests, opts ...grpc.CallOption) (*ResponseBroadcastTxs, error)
BroadcastTx(ctx context.Context, in *BroadcastEthTxWithFromRequest, opts ...grpc.CallOption) (*ResponseBroadcastTx, error)
BroadcastLegacyTx(ctx context.Context, in *BroadcastLegacyEthTxWithFromRequest, opts ...grpc.CallOption) (*ResponseLegacyEthTxBroadcastTx, error)
BroadcastLegacyTxs(ctx context.Context, in *BroadcastLegacyEthTxsWithFromRequest, opts ...grpc.CallOption) (*ResponseLegacyEthTxsBroadcastTx, error)
// web3
Sha3(ctx context.Context, in *Sha3Request, opts ...grpc.CallOption) (*Sha3Response, error)
NodeVersion(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*NodeVersionResponse, error)
......@@ -120,6 +122,24 @@ func (c *ringServiceClient) BroadcastTx(ctx context.Context, in *BroadcastEthTxW
return out, nil
}
func (c *ringServiceClient) BroadcastLegacyTx(ctx context.Context, in *BroadcastLegacyEthTxWithFromRequest, opts ...grpc.CallOption) (*ResponseLegacyEthTxBroadcastTx, error) {
out := new(ResponseLegacyEthTxBroadcastTx)
err := c.cc.Invoke(ctx, "/ring.v1.RingService/BroadcastLegacyTx", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *ringServiceClient) BroadcastLegacyTxs(ctx context.Context, in *BroadcastLegacyEthTxsWithFromRequest, opts ...grpc.CallOption) (*ResponseLegacyEthTxsBroadcastTx, error) {
out := new(ResponseLegacyEthTxsBroadcastTx)
err := c.cc.Invoke(ctx, "/ring.v1.RingService/BroadcastLegacyTxs", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *ringServiceClient) Sha3(ctx context.Context, in *Sha3Request, opts ...grpc.CallOption) (*Sha3Response, error) {
out := new(Sha3Response)
err := c.cc.Invoke(ctx, "/ring.v1.RingService/Sha3", in, out, opts...)
......@@ -548,9 +568,11 @@ func (c *ringServiceClient) Logs(ctx context.Context, in *LogsRequest, opts ...g
// for forward compatibility
type RingServiceServer interface {
Ping(context.Context, *RequestPing) (*ResponsePing, error)
// rpc BroadcastTx(RequestBroadcastTx) returns (ResponseBroadcastTx);
//rpc BroadcastTx(RequestBroadcastTx) returns (ResponseBroadcastTx);
BroadcastTxs(context.Context, *BroadcastEthTxWithFromRequests) (*ResponseBroadcastTxs, error)
BroadcastTx(context.Context, *BroadcastEthTxWithFromRequest) (*ResponseBroadcastTx, error)
BroadcastLegacyTx(context.Context, *BroadcastLegacyEthTxWithFromRequest) (*ResponseLegacyEthTxBroadcastTx, error)
BroadcastLegacyTxs(context.Context, *BroadcastLegacyEthTxsWithFromRequest) (*ResponseLegacyEthTxsBroadcastTx, error)
// web3
Sha3(context.Context, *Sha3Request) (*Sha3Response, error)
NodeVersion(context.Context, *emptypb.Empty) (*NodeVersionResponse, error)
......@@ -623,6 +645,12 @@ func (UnimplementedRingServiceServer) BroadcastTxs(context.Context, *BroadcastEt
func (UnimplementedRingServiceServer) BroadcastTx(context.Context, *BroadcastEthTxWithFromRequest) (*ResponseBroadcastTx, error) {
return nil, status.Errorf(codes.Unimplemented, "method BroadcastTx not implemented")
}
func (UnimplementedRingServiceServer) BroadcastLegacyTx(context.Context, *BroadcastLegacyEthTxWithFromRequest) (*ResponseLegacyEthTxBroadcastTx, error) {
return nil, status.Errorf(codes.Unimplemented, "method BroadcastLegacyTx not implemented")
}
func (UnimplementedRingServiceServer) BroadcastLegacyTxs(context.Context, *BroadcastLegacyEthTxsWithFromRequest) (*ResponseLegacyEthTxsBroadcastTx, error) {
return nil, status.Errorf(codes.Unimplemented, "method BroadcastLegacyTxs not implemented")
}
func (UnimplementedRingServiceServer) Sha3(context.Context, *Sha3Request) (*Sha3Response, error) {
return nil, status.Errorf(codes.Unimplemented, "method Sha3 not implemented")
}
......@@ -831,6 +859,42 @@ func _RingService_BroadcastTx_Handler(srv interface{}, ctx context.Context, dec
return interceptor(ctx, in, info, handler)
}
func _RingService_BroadcastLegacyTx_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(BroadcastLegacyEthTxWithFromRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(RingServiceServer).BroadcastLegacyTx(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ring.v1.RingService/BroadcastLegacyTx",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(RingServiceServer).BroadcastLegacyTx(ctx, req.(*BroadcastLegacyEthTxWithFromRequest))
}
return interceptor(ctx, in, info, handler)
}
func _RingService_BroadcastLegacyTxs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(BroadcastLegacyEthTxsWithFromRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(RingServiceServer).BroadcastLegacyTxs(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ring.v1.RingService/BroadcastLegacyTxs",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(RingServiceServer).BroadcastLegacyTxs(ctx, req.(*BroadcastLegacyEthTxsWithFromRequest))
}
return interceptor(ctx, in, info, handler)
}
func _RingService_Sha3_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Sha3Request)
if err := dec(in); err != nil {
......@@ -1696,6 +1760,14 @@ var RingService_ServiceDesc = grpc.ServiceDesc{
MethodName: "BroadcastTx",
Handler: _RingService_BroadcastTx_Handler,
},
{
MethodName: "BroadcastLegacyTx",
Handler: _RingService_BroadcastLegacyTx_Handler,
},
{
MethodName: "BroadcastLegacyTxs",
Handler: _RingService_BroadcastLegacyTxs_Handler,
},
{
MethodName: "Sha3",
Handler: _RingService_Sha3_Handler,
......
......@@ -8,6 +8,13 @@ require (
google.golang.org/protobuf v1.28.1
)
require (
github.com/ghodss/yaml v1.0.0 // indirect
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b // indirect
github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
require (
github.com/CaduceusMetaverseProtocol/MetaTypes v1.0.0
github.com/btcsuite/btcd/btcec/v2 v2.2.0 // indirect
......
This diff is collapsed.
......@@ -133,25 +133,22 @@ message NonceResponse {
uint64 nonce = 3;
}
message RepeatedNonceRequest {
// request address
repeated base.v1.Address address = 1[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
repeated bytes address = 1;
// request block number
repeated base.v1.BigInt block_id = 2[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
repeated bytes block_id = 2;
}
message RepeatedNonceResponse {
// request address
repeated base.v1.Address address = 1[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
// request block number
repeated base.v1.BigInt block_id = 2[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
// the address
repeated bytes address = 1;
// block height
repeated bytes block_id = 2;
// nonce
repeated uint64 nonce = 3;
}
message TransactionCountRequest {
// request address
base.v1.Address address = 1[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
......
......@@ -136,18 +136,25 @@ message NonceResponse {
message RepeatedNonceRequest {
// request address
repeated base.v1.Address address = 1[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
// repeated base.v1.Address address = 1[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
//repeated bytes addresses =1;
// request block number
repeated base.v1.BigInt block_id = 2[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
//repeated base.v1.BigInt block_id = 2[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
repeated NonceRequest list=1;
}
message RepeatedNonceResponse {
// request address
repeated base.v1.Address address = 1[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
// request block number
repeated base.v1.BigInt block_id = 2[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
// nonce
repeated uint64 nonce = 3;
//repeated base.v1.Address address = 1[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
// repeated bytes addresses =1;
// // request block number
// repeated base.v1.BigInt block_id = 2[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
// // nonce
// repeated uint64 nonce = 3;
repeated NonceResponse list=1;
}
......
......@@ -11,18 +11,63 @@ import "base/v1/eth_tx.proto";
message RequestBroadcastTx {
bytes tx = 1;
}
message ResponseBroadcastTx {
bytes hash =1;
}
message broadcastEthTxWithFromRequest{
base.v1.EthTransaction ethTx =1;
string from =2;
}
message broadcastLegacyEthTxWithFromRequest{
base.v1.EthLegacyTx LegacyTx =1;
string from =2;
}
message ResponseLegacyEthTxBroadcastTx {
bytes hash =1;
}
message broadcastLegacyEthTxsWithFromRequest{
repeated broadcastLegacyEthTxWithFromRequest list =1;
}
message ResponseLegacyEthTxsBroadcastTx {
repeated ResponseLegacyEthTxBroadcastTx list=1;
}
message broadcastEthTxWithFromRequests{
repeated broadcastEthTxWithFromRequest list =1;
}
message ResponseBroadcastTxs{
repeated ResponseBroadcastTx list =1;
}
service RingService{
rpc Ping(RequestPing) returns (ResponsePing);
//rpc BroadcastTx(RequestBroadcastTx) returns (ResponseBroadcastTx);
rpc BroadcastTxs(broadcastEthTxWithFromRequests) returns (ResponseBroadcastTxs);
rpc BroadcastTx(broadcastEthTxWithFromRequest) returns (ResponseBroadcastTx);
rpc BroadcastLegacyTx(broadcastLegacyEthTxWithFromRequest) returns (ResponseLegacyEthTxBroadcastTx);
rpc BroadcastLegacyTxs(broadcastLegacyEthTxsWithFromRequest) returns (ResponseLegacyEthTxsBroadcastTx);
// web3
rpc Sha3(Sha3Request) returns (Sha3Response) {};
......@@ -100,10 +145,3 @@ message RequestPing {}
message ResponsePing {}
message RequestBroadcastTx {
bytes tx = 1;
}
message ResponseBroadcastTx {
bytes hash =1;
}
\ No newline at end of file
......@@ -2,7 +2,8 @@
"receiveAddr": "0x0Fb196385c8826e3806ebA2cA2cb78B26E08fEEe",
"count": 100,
"type": 1,
"rpcNode": "54.168.125.67:8545",
"rpcNode": "54.168.125.67:5001",
"grpcNode": "18.183.99.139:38002",
"amount": 10000000,
"chainId": 100,
"initAccountPrv": "FD5CC6F5E7E2805E920AC5DC83D5AF1106F9C92F0C04F9D5E1FD4261B4B4464A",
......
......@@ -22,7 +22,7 @@ func init() {
startCmd.PersistentFlags().StringVar(&cpuProfile, "cpuProfile", "cpuProfile.prof", "Statistics cpu profile")
startCmd.PersistentFlags().IntVar(&startCount, "startCount", 0, "read excel start count")
startCmd.PersistentFlags().IntVar(&endCount, "endCount", 100, "read excel end count")
startCmd.PersistentFlags().BoolVar(&broadcastTxArr, "broadcastTxArr", false, "test grpc interface -> broadcastTxArr")
startCmd.PersistentFlags().BoolVar(&broadcastTxArr, "broadcastTxArr", true, "test grpc interface -> broadcastTxArr")
startCmd.PersistentFlags().IntVar(&txCount, "txCount", 1000, "send tran count")
startCmd.PersistentFlags().IntVar(&goRoutineCount, "goRoutineCount", 10, "send tran goRoutine count")
startCmd.PersistentFlags().IntVar(&batchCount, "batchCount", 100, "batch send tran count")
......
......@@ -4,13 +4,13 @@ import (
"ChainGrpcTest/log"
"ChainGrpcTest/tool"
"ChainGrpcTest/transaction"
"github.com/ethereum/go-ethereum/core/types"
basev1 "github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/base/v1"
"sync"
)
var (
SendTxAccountArr [][]string
tranArrChan chan []*types.Transaction
tranArrChan chan []*basev1.MetaTxBase
)
func init() {
......@@ -21,7 +21,7 @@ func init() {
return
}
cfg.StorageAccFileName += ".xlsx"
tranArrChan = make(chan []*types.Transaction, 10000)
tranArrChan = make(chan []*basev1.MetaTxBase, 10000)
}
func startTest() {
......@@ -49,7 +49,8 @@ func startTest() {
}()
for {
log.Info("----------------------------------start")
arr := transaction.SignedTxArr(syncMap, SendTxAccountArr, cfg)
//arr := transaction.SignedTxArr(syncMap, SendTxAccountArr, cfg)
arr := transaction.GrpcSignedTxArr(syncMap, SendTxAccountArr, cfg)
log.Info("----------------------------------end")
tranArrChan <- arr
syncMap = updateNonce(syncMap, cfg)
......
......@@ -15,6 +15,7 @@ type Config struct {
GoRoutineCount int `json:"goRoutineCount"`
Type int `json:"type"`
RpcNode string `json:"rpcNode"`
GrpcNode string `json:"grpcNode"`
Amount int64 `json:"amount"`
ChainId int64 `json:"chainId"`
InitAccountPrv string `json:"initAccountPrv"`
......
......@@ -3,12 +3,9 @@ package transaction
import (
"ChainGrpcTest/log"
"ChainGrpcTest/tool"
"ChainGrpcTest/txcache"
"context"
v1 "github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/base/v1"
ring "github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/ring/v1"
metatypes "github.com/CaduceusMetaverseProtocol/MetaTypes/types"
"github.com/ethereum/go-ethereum/core/types"
gogotypes "github.com/gogo/protobuf/types"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
......@@ -25,7 +22,7 @@ func init() {
broadcastEthTxWithFromRequestsArr = make(chan *ring.BroadcastEthTxWithFromRequests, 1000000)
}
func BroadcastTxArr(tranArr []*types.Transaction, cfg *tool.Config) error {
func BroadcastTxArr(tranArr []*v1.MetaTxBase, cfg *tool.Config) error {
client, err := grpc.Dial(cfg.RpcNode, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return err
......@@ -44,9 +41,7 @@ func BroadcastTxArr(tranArr []*types.Transaction, cfg *tool.Config) error {
if err != nil {
log.Error("gogo types.MarshalAny error:", err)
}
fromAddr, _ := txcache.GetFromAddr(tranArr[i].Hash().Hex())
request := ring.BroadcastEthTxWithFromRequest{
From: fromAddr,
EthTx: &v1.EthTransaction{Tx: ethTxAsAny},
}
ethTxArr = append(ethTxArr, &request)
......@@ -92,25 +87,17 @@ func broadcastTx(cfg *tool.Config, client ring.RingServiceClient) error {
}
}
func constructionEthLegacyTx(tran *types.Transaction) v1.EthLegacyTx {
v, r, s := tran.RawSignatureValues()
toAddr := metatypes.BytesToAddress(tran.To().Bytes())
nv := metatypes.NewBigInt(0)
nv.Set(v)
nr := metatypes.NewBigInt(0)
nr.Set(r)
ns := metatypes.NewBigInt(0)
ns.Set(s)
func constructionEthLegacyTx(tran *v1.MetaTxBase) v1.EthLegacyTx {
rawTx := v1.EthLegacyTx{
Nonce: tran.Nonce(),
GasPrice: metatypes.NewBigInt(tran.GasPrice().Int64()),
Gas: tran.Gas(),
To: &toAddr,
Value: metatypes.NewBigInt(tran.Value().Int64()),
Data: tran.Data(),
V: nv,
R: nr,
S: ns,
Nonce: tran.Nonce,
GasPrice: tran.GasPrice,
Gas: tran.Gas,
To: tran.To,
Value: tran.Value,
Data: tran.Data,
V: tran.V,
R: tran.R,
S: tran.S,
}
return rawTx
}
......@@ -6,15 +6,16 @@ import (
"ChainGrpcTest/txcache"
"context"
"crypto/ecdsa"
ring "github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/ring/v1"
basev1 "github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/base/v1"
crypterv1 "github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/crypter/v1"
metatypes "github.com/CaduceusMetaverseProtocol/MetaTypes/types"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"math/big"
"net"
"strconv"
"strings"
"sync"
"sync/atomic"
......@@ -41,11 +42,20 @@ type SignTranArr struct {
mux sync.RWMutex
}
type GrpcSignTranArr struct {
TranArr []*basev1.MetaTxBase
mux sync.RWMutex
}
var (
tran = make(chan *Transactor, 0)
grpcTran = make(chan *crypterv1.BatchSignTxRequest, 0)
signTranArr = &SignTranArr{
TranArr: make([]*types.Transaction, 0),
}
grpcSignTranArr = &GrpcSignTranArr{
TranArr: make([]*basev1.MetaTxBase, 0),
}
batchSignCount, handleNonceCount int32
)
......@@ -97,26 +107,26 @@ func InitAccNonce(sendTxAccountArr [][]string, cfg *tool.Config) (error, sync.Ma
return err, sync.Map{}
}
defer client.Close()
serviceClient := ring.NewRingServiceClient(client)
//serviceClient := ring.NewRingServiceClient(client)
for i := 0; i < cfg.GoRoutineCount; i++ {
go func() {
for {
select {
case sendTxAccount := <-rowsCh:
addressRow := sendTxAccount[0]
//addressRow := sendTxAccount[0]
privateKey := sendTxAccount[1]
fromAddr := metatypes.HexToAddress(addressRow)
nonceReq := &ring.NonceRequest{
Address: (*metatypes.Address)(fromAddr.Bytes()),
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
defer cancel()
response, err := serviceClient.Nonce(ctx, nonceReq)
//fromAddr := metatypes.HexToAddress(addressRow)
//nonceReq := &ring.NonceRequest{
// Address: (*metatypes.Address)(fromAddr.Bytes()),
//}
//ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
//defer cancel()
//response, err := serviceClient.Nonce(ctx, nonceReq)
if err != nil {
log.Error("get account nonce error:", err)
}
intNum, _ := strconv.Atoi(strconv.FormatUint(response.Nonce, 10))
accountsNonceMap.Store(privateKey, intNum)
//intNum, _ := strconv.Atoi(strconv.FormatUint(response.Nonce, 10))
accountsNonceMap.Store(privateKey, 0)
atomic.AddInt32(&handleNonceCount, 1)
}
}
......@@ -206,6 +216,92 @@ func signedTxFunc() (*types.Transaction, error) {
}
}
// GrpcSignedTxArr 获取全部签名数据
func GrpcSignedTxArr(syncMap sync.Map, sendTxAccountArr [][]string, cfg *tool.Config) []*basev1.MetaTxBase {
client, err := grpc.Dial(cfg.GrpcNode, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Error("dial nebula failed", "err", err)
}
serviceClient := crypterv1.NewCrypterServiceClient(client)
for i := 0; i < cfg.GoRoutineCount; i++ {
go grpcSignedTxFunc(serviceClient)
}
for _, rows := range sendTxAccountArr {
fromAddr := rows[0]
privateKey := rows[1]
value, ok := syncMap.Load(privateKey)
if !ok {
log.Error("Load nonce map error...........")
continue
}
nonce := new(big.Int).SetInt64(int64(value.(int)))
log.Infof("from addr:%s,nonce:%d", fromAddr, nonce)
rawTxArr := make([]*basev1.MetaTxBase, 0)
prv, err := crypto.HexToECDSA(privateKey)
if err != nil {
return nil
}
for signCount := 0; signCount < cfg.SignCount; signCount++ {
toAddress := metatypes.HexToAddress(cfg.ReceiveAddr)
base := &basev1.MetaTxBase{
ChainId: metatypes.NewBigInt(cfg.ChainId),
Nonce: nonce.Uint64(),
GasPrice: metatypes.NewBigInt(1000000001),
Gas: metatypes.NewBigInt(300000).Uint64(),
To: &toAddress,
Value: metatypes.NewBigInt(cfg.Amount),
Data: nil,
}
rawTxArr = append(rawTxArr, base)
if err != nil {
log.Errorf("signed tx error %s ", err)
continue
}
nonce = big.NewInt(1).Add(nonce, big.NewInt(1))
}
requestMetaTx := crypterv1.BatchSignTxRequest{
RawTx: rawTxArr,
Private: prv.D.Bytes(),
}
grpcTran <- &requestMetaTx
}
for {
if len(sendTxAccountArr)*cfg.SignCount == int(batchSignCount) && len(grpcSignTranArr.TranArr) == len(sendTxAccountArr)*cfg.SignCount {
batchSignCount = 0
newTranArr := make([]*basev1.MetaTxBase, 0)
for _, tran := range grpcSignTranArr.TranArr {
newTranArr = append(newTranArr, tran)
}
grpcSignTranArr.TranArr = make([]*basev1.MetaTxBase, 0)
return newTranArr
}
}
}
// grpcSignedTxFunc 签名本币转账交易
func grpcSignedTxFunc(client crypterv1.CrypterServiceClient) (*types.Transaction, error) {
for {
select {
case t := <-grpcTran:
tx, err := client.BatchSignTx(context.Background(), t)
if err != nil {
return nil, err
}
AddGrpcTran(tx.GetSignedTx())
}
}
}
func AddGrpcTran(grpcSignTx []*basev1.MetaTxBase) {
grpcSignTranArr.mux.Lock()
defer grpcSignTranArr.mux.Unlock()
for _, txBase := range grpcSignTx {
grpcSignTranArr.TranArr = append(grpcSignTranArr.TranArr, txBase)
atomic.AddInt32(&batchSignCount, 1)
}
}
func Add(signedTx *types.Transaction) {
signTranArr.mux.Lock()
defer signTranArr.mux.Unlock()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment