service and command

This commit is contained in:
Ian Norden 2020-10-14 12:29:14 -05:00
parent 582296fccd
commit e441254891
9 changed files with 144 additions and 150 deletions

View File

@ -16,36 +16,42 @@
package cmd package cmd
import ( import (
"fmt" "os"
"os/signal"
"sync"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/vulcanize/tx_spammer/pkg"
) )
// sendTxsCmd represents the sendTxs command // sendTxsCmd represents the sendTxs command
var sendTxsCmd = &cobra.Command{ var sendTxsCmd = &cobra.Command{
Use: "sendTxs", Use: "sendTxs",
Short: "A brief description of your command", Short: "send large volumes of different tx types to different nodes",
Long: `A longer description that spans multiple lines and likely contains examples Long: `Loads tx configuration from .toml config file
and usage of using your command. For example: Generates txs from configuration and sends them to designated node according to set frequency and number`,
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
fmt.Println("sendTxs called") sendTxs()
}, },
} }
func sendTxs() {
params, err := tx_spammer.NewTxParams()
if err != nil {
logWithCommand.Fatal(err)
}
txSpammer := tx_spammer.NewTxSpammer(params)
wg := new(sync.WaitGroup)
quitChan := make(chan bool)
txSpammer.Loop(wg, quitChan)
shutdown := make(chan os.Signal)
signal.Notify(shutdown, os.Interrupt)
<-shutdown
close(quitChan)
wg.Wait()
}
func init() { func init() {
rootCmd.AddCommand(sendTxsCmd) rootCmd.AddCommand(sendTxsCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// sendTxsCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// sendTxsCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
} }

View File

@ -1,5 +1,5 @@
[eth] [eth]
txs = ["L2ContractPutCall", "L2ContractGetCall"] txs = ["L2ContractDeployment", "L2ContractPutCall", "L2ContractGetCall"]
[L2ContractDeployment] [L2ContractDeployment]
type = "L2" type = "L2"
@ -11,8 +11,8 @@
data = "" data = ""
senderKeyPath = "" senderKeyPath = ""
writeSenderPath = "" writeSenderPath = ""
frequency = 15 frequency = 1
totalNumber = 1500 totalNumber = 1
chainID = 420 chainID = 420
[L2ContractPutCall] [L2ContractPutCall]

View File

@ -40,21 +40,21 @@ type TxParams struct {
Type TxType Type TxType
// Universal tx fields // Universal tx fields
To *common.Address To *common.Address
GasLimit uint64 GasLimit uint64
GasPrice *big.Int // nil if eip1559 GasPrice *big.Int // nil if eip1559
Amount *big.Int Amount *big.Int
Data []byte Data []byte
Sender common.Address Sender common.Address
// Optimism-specific metadata fields // Optimism-specific metadata fields
L1SenderAddr *common.Address L1SenderAddr *common.Address
L1RollupTxId uint64 L1RollupTxId uint64
SigHashType uint8 SigHashType uint8
// EIP1559-specific fields // EIP1559-specific fields
GasPremium *big.Int GasPremium *big.Int
FeeCap *big.Int FeeCap *big.Int
// Sender key, if left the senderKeyPath is empty we generate a new key // Sender key, if left the senderKeyPath is empty we generate a new key
SenderKey *ecdsa.PrivateKey SenderKey *ecdsa.PrivateKey
@ -71,22 +71,22 @@ type TxParams struct {
const ( const (
ETH_TX_LIST = "ETH_TX_LIST" ETH_TX_LIST = "ETH_TX_LIST"
typeSuffix = ".type" typeSuffix = ".type"
httpPathSuffix = ".http" httpPathSuffix = ".http"
toSuffix = ".to" toSuffix = ".to"
amountSuffix = ".amount" amountSuffix = ".amount"
gasLimitSuffix = ".gasLimit" gasLimitSuffix = ".gasLimit"
gasPriceSuffix = ".gasPrice" gasPriceSuffix = ".gasPrice"
gasPremiumSuffix = ".gasPremium" gasPremiumSuffix = ".gasPremium"
feeCapSuffix = ".feeCap" feeCapSuffix = ".feeCap"
dataSuffix = ".data" dataSuffix = ".data"
senderKeyPathSuffix = ".senderKeyPath" senderKeyPathSuffix = ".senderKeyPath"
writeSenderPathSuffix = ".writeSenderPath" writeSenderPathSuffix = ".writeSenderPath"
l1SenderSuffix = ".l1Sender" l1SenderSuffix = ".l1Sender"
l1RollupTxIdSuffix = ".l1RollupTxId" l1RollupTxIdSuffix = ".l1RollupTxId"
sigHashTypeSuffix = ".sigHashType" sigHashTypeSuffix = ".sigHashType"
frequencySuffix = ".frequency" frequencySuffix = ".frequency"
totalNumberSuffix = ".totalNumber" totalNumberSuffix = ".totalNumber"
) )
// NewConfig returns a new tx spammer config // NewConfig returns a new tx spammer config
@ -97,7 +97,7 @@ func NewTxParams() ([]TxParams, error) {
txParams := make([]TxParams, len(txs)) txParams := make([]TxParams, len(txs))
for i, txName := range txs { for i, txName := range txs {
// Get http client // Get http client
httpPathStr := viper.GetString(txName+httpPathSuffix) httpPathStr := viper.GetString(txName + httpPathSuffix)
if httpPathStr == "" { if httpPathStr == "" {
return nil, fmt.Errorf("tx %s is missing an httpPath", txName) return nil, fmt.Errorf("tx %s is missing an httpPath", txName)
} }
@ -110,7 +110,7 @@ func NewTxParams() ([]TxParams, error) {
} }
// Get tx type // Get tx type
txTypeStr := viper.GetString(txName+typeSuffix) txTypeStr := viper.GetString(txName + typeSuffix)
if txTypeStr == "" { if txTypeStr == "" {
return nil, fmt.Errorf("need tx type for tx %s", txName) return nil, fmt.Errorf("need tx type for tx %s", txName)
} }
@ -120,20 +120,20 @@ func NewTxParams() ([]TxParams, error) {
} }
// Get basic fields // Get basic fields
toStr := viper.GetString(txName+toSuffix) toStr := viper.GetString(txName + toSuffix)
var toAddr *common.Address var toAddr *common.Address
if toStr != "" { if toStr != "" {
to := common.HexToAddress(toStr) to := common.HexToAddress(toStr)
toAddr = &to toAddr = &to
} }
amountStr := viper.GetString(txName+amountSuffix) amountStr := viper.GetString(txName + amountSuffix)
amount := new(big.Int) amount := new(big.Int)
if amountStr != "" { if amountStr != "" {
if _, ok := amount.SetString(amountStr, 10); !ok { if _, ok := amount.SetString(amountStr, 10); !ok {
return nil, fmt.Errorf("amount (%s) for tx %s is not valid", amountStr, txName) return nil, fmt.Errorf("amount (%s) for tx %s is not valid", amountStr, txName)
} }
} }
gasPriceStr := viper.GetString(txName+gasPriceSuffix) gasPriceStr := viper.GetString(txName + gasPriceSuffix)
var gasPrice *big.Int var gasPrice *big.Int
if gasPriceStr != "" { if gasPriceStr != "" {
gasPrice = new(big.Int) gasPrice = new(big.Int)
@ -141,15 +141,15 @@ func NewTxParams() ([]TxParams, error) {
return nil, fmt.Errorf("gasPrice (%s) for tx %s is not valid", gasPriceStr, txName) return nil, fmt.Errorf("gasPrice (%s) for tx %s is not valid", gasPriceStr, txName)
} }
} }
gasLimit := viper.GetUint64(txName+gasLimitSuffix) gasLimit := viper.GetUint64(txName + gasLimitSuffix)
hex := viper.GetString(txName+dataSuffix) hex := viper.GetString(txName + dataSuffix)
data := make([]byte, 0) data := make([]byte, 0)
if hex != "" { if hex != "" {
data = common.Hex2Bytes(hex) data = common.Hex2Bytes(hex)
} }
// Load or generate sender key // Load or generate sender key
senderKeyPath := viper.GetString(txName+senderKeyPathSuffix) senderKeyPath := viper.GetString(txName + senderKeyPathSuffix)
var key *ecdsa.PrivateKey var key *ecdsa.PrivateKey
if senderKeyPath != "" { if senderKeyPath != "" {
key, err = crypto.LoadECDSA(senderKeyPath) key, err = crypto.LoadECDSA(senderKeyPath)
@ -161,7 +161,7 @@ func NewTxParams() ([]TxParams, error) {
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to generate ecdsa key for tx %s", txName) return nil, fmt.Errorf("unable to generate ecdsa key for tx %s", txName)
} }
writePath := viper.GetString(txName+writeSenderPathSuffix) writePath := viper.GetString(txName + writeSenderPathSuffix)
if writePath != "" { if writePath != "" {
if err := crypto.SaveECDSA(writePath, key); err != nil { if err := crypto.SaveECDSA(writePath, key); err != nil {
return nil, err return nil, err
@ -170,25 +170,25 @@ func NewTxParams() ([]TxParams, error) {
} }
// Attempt to load Optimism fields // Attempt to load Optimism fields
l1SenderStr := viper.GetString(txName+l1SenderSuffix) l1SenderStr := viper.GetString(txName + l1SenderSuffix)
var l1Sender *common.Address var l1Sender *common.Address
if l1SenderStr != "" { if l1SenderStr != "" {
sender := common.HexToAddress(l1SenderStr) sender := common.HexToAddress(l1SenderStr)
l1Sender = &sender l1Sender = &sender
} }
l1RollupTxId := viper.GetUint64(txName+l1RollupTxIdSuffix) l1RollupTxId := viper.GetUint64(txName + l1RollupTxIdSuffix)
sigHashType := viper.GetUint(txName+sigHashTypeSuffix) sigHashType := viper.GetUint(txName + sigHashTypeSuffix)
// If gasPrice was empty, attempt to load EIP1559 fields // If gasPrice was empty, attempt to load EIP1559 fields
var feeCap, gasPremium *big.Int var feeCap, gasPremium *big.Int
if gasPrice == nil { if gasPrice == nil {
feeCapStr := viper.GetString(txName+feeCapSuffix) feeCapStr := viper.GetString(txName + feeCapSuffix)
gasPremiumString := viper.GetString(txName+gasPremiumSuffix) gasPremiumString := viper.GetString(txName + gasPremiumSuffix)
if feeCapStr == "" { if feeCapStr == "" {
return nil, fmt.Errorf("tx %s is missing feeCapStr", txName) return nil, fmt.Errorf("tx %s is missing feeCapStr", txName)
} }
if gasPremiumString == "" { if gasPremiumString == "" {
return nil, fmt.Errorf("tx %s is missing gasPremiumStr", txName) return nil, fmt.Errorf("tx %s is missing gasPremiumStr", txName)
} }
feeCap = new(big.Int) feeCap = new(big.Int)
@ -202,25 +202,25 @@ func NewTxParams() ([]TxParams, error) {
} }
// Load the sending paramas // Load the sending paramas
frequency := viper.GetDuration(txName+frequencySuffix) frequency := viper.GetDuration(txName + frequencySuffix)
totalNumber := viper.GetUint64(txName+totalNumberSuffix) totalNumber := viper.GetUint64(txName + totalNumberSuffix)
txParams[i] = TxParams{ txParams[i] = TxParams{
Client: rpcClient, Client: rpcClient,
Type: txType, Type: txType,
Name: txName, Name: txName,
To: toAddr, To: toAddr,
Amount: amount, Amount: amount,
GasLimit: gasLimit, GasLimit: gasLimit,
GasPrice: gasPrice, GasPrice: gasPrice,
GasPremium: gasPremium, GasPremium: gasPremium,
FeeCap: feeCap, FeeCap: feeCap,
Data: data, Data: data,
L1SenderAddr: l1Sender, L1SenderAddr: l1Sender,
L1RollupTxId: l1RollupTxId, L1RollupTxId: l1RollupTxId,
SigHashType: uint8(sigHashType), SigHashType: uint8(sigHashType),
Frequency: frequency, Frequency: frequency,
TotalNumber: totalNumber, TotalNumber: totalNumber,
} }
} }
return txParams, nil return txParams, nil

View File

@ -19,58 +19,10 @@ package tx_spammer
import ( import (
"context" "context"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
) )
// SendTxArgs represents the arguments to submit a transaction
type SendTxArgs struct {
From common.MixedcaseAddress `json:"from"`
To *common.MixedcaseAddress `json:"to"`
Gas hexutil.Uint64 `json:"gas"`
GasPrice hexutil.Big `json:"gasPrice"`
Value hexutil.Big `json:"value"`
Nonce hexutil.Uint64 `json:"nonce"`
// We accept "data" and "input" for backwards-compatibility reasons.
Data *hexutil.Bytes `json:"data"`
Input *hexutil.Bytes `json:"input,omitempty"`
}
/*
// SendTransaction creates a transaction for the given argument, sign it and submit it to the
// transaction pool.
func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) {
// Look up the wallet containing the requested signer
account := accounts.Account{Address: args.From}
wallet, err := s.b.AccountManager().Find(account)
if err != nil {
return common.Hash{}, err
}
if args.Nonce == nil {
// Hold the addresse's mutex around signing to prevent concurrent assignment of
// the same nonce to multiple accounts.
s.nonceLock.LockAddr(args.From)
defer s.nonceLock.UnlockAddr(args.From)
}
// Set some sanity defaults and terminate on failure
if err := args.setDefaults(ctx, s.b); err != nil {
return common.Hash{}, err
}
// Assemble the transaction and sign with the wallet
tx := args.toTransaction()
signed, err := wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
if err != nil {
return common.Hash{}, err
}
return SubmitTransaction(ctx, s.b, signed)
}
*/
type TxSender struct { type TxSender struct {
TxGen *TxGenerator TxGen *TxGenerator
} }
@ -80,10 +32,15 @@ func NewTxSender(params []TxParams) *TxSender {
TxGen: NewTxGenerator(params), TxGen: NewTxGenerator(params),
} }
} }
func (s *TxSender) Send() <-chan error { func (s *TxSender) Send(quitChan <-chan bool) <-chan error {
errChan := make(chan error) errChan := make(chan error)
go func() { go func() {
for s.TxGen.Next() { for s.TxGen.Next() {
select {
case <-quitChan:
return
default:
}
if err := sendRawTransaction(s.TxGen.Current()); err != nil { if err := sendRawTransaction(s.TxGen.Current()); err != nil {
errChan <- err errChan <- err
} }
@ -92,8 +49,9 @@ func (s *TxSender) Send() <-chan error {
errChan <- s.TxGen.Error() errChan <- s.TxGen.Error()
} }
}() }()
return errChan
} }
func sendRawTransaction(rpcClient *rpc.Client, txRlp []byte) error { func sendRawTransaction(rpcClient *rpc.Client, txRlp []byte) error {
return rpcClient.CallContext(context.Background(), nil, "eth_sendRawTransaction", hexutil.Encode(txRlp)) return rpcClient.CallContext(context.Background(), nil, "eth_sendRawTransaction", hexutil.Encode(txRlp))
} }

View File

@ -16,19 +16,39 @@
package tx_spammer package tx_spammer
import "sync" import (
"sync"
"github.com/sirupsen/logrus"
)
type Service interface { type Service interface {
Loop(wg *sync.WaitGroup) error Loop(wg *sync.WaitGroup, quitChan <-chan bool)
} }
type Tx struct { type Spammer struct {
Spammer *Sender Sender *TxSender
Generator *TxGenerator
Config *Config
} }
func NewTxSpammer(params []TxParams) (TxSpammer, error) { func NewTxSpammer(params []TxParams) Service {
return &Spammer{
return &txSpammer{}, nil Sender: NewTxSender(params),
}
}
func (s *Spammer) Loop(wg *sync.WaitGroup, quitChan <-chan bool) {
forwardQuit := make(chan bool)
errChan := s.Sender.Send(forwardQuit)
go func() {
wg.Add(1)
defer wg.Done()
for {
select {
case err := <-errChan:
logrus.Error(err)
case forwardQuit <- <-quitChan:
return
}
}
}()
} }

View File

View File

@ -20,10 +20,10 @@ import "github.com/ethereum/go-ethereum/rpc"
// TxGenerator generates and signs txs // TxGenerator generates and signs txs
type TxGenerator struct { type TxGenerator struct {
TxParams []TxParams TxParams []TxParams
currentTx []byte currentTx []byte
currentClient *rpc.Client currentClient *rpc.Client
err error err error
} }
func NewTxGenerator(params []TxParams) *TxGenerator { func NewTxGenerator(params []TxParams) *TxGenerator {
@ -46,4 +46,4 @@ func (gen TxGenerator) Error() error {
func (gen TxGenerator) gen(params TxParams) ([]byte, error) { func (gen TxGenerator) gen(params TxParams) ([]byte, error) {
return nil, nil return nil, nil
} }

View File

@ -45,4 +45,4 @@ func TxTypeFromString(str string) (TxType, error) {
default: default:
return Unkown, fmt.Errorf("unsupported tx type: %s", str) return Unkown, fmt.Errorf("unsupported tx type: %s", str)
} }
} }

View File

@ -1,10 +1,27 @@
// VulcanizeDB
// Copyright © 2020 Vulcanize
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package tx_spammer package tx_spammer
import ( import (
"fmt" "fmt"
"math/big"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"math/big"
) )
// ChainConfig returns the appropriate ethereum chain config for the provided chain id // ChainConfig returns the appropriate ethereum chain config for the provided chain id
@ -16,9 +33,8 @@ func ChainConfig(chainID uint64) (*params.ChainConfig, error) {
return params.TestnetChainConfig, nil // Ropsten return params.TestnetChainConfig, nil // Ropsten
case 4: case 4:
return params.RinkebyChainConfig, nil return params.RinkebyChainConfig, nil
case 5: case 5, 420:
return params.GoerliChainConfig, nil return params.GoerliChainConfig, nil
case 420:
default: default:
return nil, fmt.Errorf("chain config for chainid %d not available", chainID) return nil, fmt.Errorf("chain config for chainid %d not available", chainID)
} }
@ -27,17 +43,11 @@ func ChainConfig(chainID uint64) (*params.ChainConfig, error) {
// ChainConfig returns the appropriate ethereum chain config for the provided chain id // ChainConfig returns the appropriate ethereum chain config for the provided chain id
func TxSigner(chainID uint64) (types.Signer, error) { func TxSigner(chainID uint64) (types.Signer, error) {
switch chainID { switch chainID {
case 1: case 1, 3, 4, 5:
return params.MainnetChainConfig, nil return types.NewEIP155Signer(new(big.Int).SetUint64(chainID)), nil
case 3:
return params.TestnetChainConfig, nil // Ropsten
case 4:
return params.RinkebyChainConfig, nil
case 5:
return params.GoerliChainConfig, nil
case 420: case 420:
return types.NewOVMSigner(big.NewInt()), nil return types.NewOVMSigner(new(big.Int).SetUint64(chainID)), nil
default: default:
return nil, fmt.Errorf("chain config for chainid %d not available", chainID) return nil, fmt.Errorf("chain config for chainid %d not available", chainID)
} }
} }