github.com/jimmyx0x/go-ethereum@v1.10.28/cmd/evm/internal/t8ntool/transaction.go (about)

     1  // Copyright 2021 The go-ethereum Authors
     2  // This file is part of go-ethereum.
     3  //
     4  // go-ethereum is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU 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  // go-ethereum 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 General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU General Public License
    15  // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package t8ntool
    18  
    19  import (
    20  	"encoding/json"
    21  	"errors"
    22  	"fmt"
    23  	"math/big"
    24  	"os"
    25  	"strings"
    26  
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/common/hexutil"
    29  	"github.com/ethereum/go-ethereum/core"
    30  	"github.com/ethereum/go-ethereum/core/types"
    31  	"github.com/ethereum/go-ethereum/log"
    32  	"github.com/ethereum/go-ethereum/params"
    33  	"github.com/ethereum/go-ethereum/rlp"
    34  	"github.com/ethereum/go-ethereum/tests"
    35  	"github.com/urfave/cli/v2"
    36  )
    37  
    38  type result struct {
    39  	Error        error
    40  	Address      common.Address
    41  	Hash         common.Hash
    42  	IntrinsicGas uint64
    43  }
    44  
    45  // MarshalJSON marshals as JSON with a hash.
    46  func (r *result) MarshalJSON() ([]byte, error) {
    47  	type xx struct {
    48  		Error        string          `json:"error,omitempty"`
    49  		Address      *common.Address `json:"address,omitempty"`
    50  		Hash         *common.Hash    `json:"hash,omitempty"`
    51  		IntrinsicGas hexutil.Uint64  `json:"intrinsicGas,omitempty"`
    52  	}
    53  	var out xx
    54  	if r.Error != nil {
    55  		out.Error = r.Error.Error()
    56  	}
    57  	if r.Address != (common.Address{}) {
    58  		out.Address = &r.Address
    59  	}
    60  	if r.Hash != (common.Hash{}) {
    61  		out.Hash = &r.Hash
    62  	}
    63  	out.IntrinsicGas = hexutil.Uint64(r.IntrinsicGas)
    64  	return json.Marshal(out)
    65  }
    66  
    67  func Transaction(ctx *cli.Context) error {
    68  	// Configure the go-ethereum logger
    69  	glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false)))
    70  	glogger.Verbosity(log.Lvl(ctx.Int(VerbosityFlag.Name)))
    71  	log.Root().SetHandler(glogger)
    72  
    73  	var (
    74  		err error
    75  	)
    76  	// We need to load the transactions. May be either in stdin input or in files.
    77  	// Check if anything needs to be read from stdin
    78  	var (
    79  		txStr       = ctx.String(InputTxsFlag.Name)
    80  		inputData   = &input{}
    81  		chainConfig *params.ChainConfig
    82  	)
    83  	// Construct the chainconfig
    84  	if cConf, _, err := tests.GetChainConfig(ctx.String(ForknameFlag.Name)); err != nil {
    85  		return NewError(ErrorConfig, fmt.Errorf("failed constructing chain configuration: %v", err))
    86  	} else {
    87  		chainConfig = cConf
    88  	}
    89  	// Set the chain id
    90  	chainConfig.ChainID = big.NewInt(ctx.Int64(ChainIDFlag.Name))
    91  	var body hexutil.Bytes
    92  	if txStr == stdinSelector {
    93  		decoder := json.NewDecoder(os.Stdin)
    94  		if err := decoder.Decode(inputData); err != nil {
    95  			return NewError(ErrorJson, fmt.Errorf("failed unmarshaling stdin: %v", err))
    96  		}
    97  		// Decode the body of already signed transactions
    98  		body = common.FromHex(inputData.TxRlp)
    99  	} else {
   100  		// Read input from file
   101  		inFile, err := os.Open(txStr)
   102  		if err != nil {
   103  			return NewError(ErrorIO, fmt.Errorf("failed reading txs file: %v", err))
   104  		}
   105  		defer inFile.Close()
   106  		decoder := json.NewDecoder(inFile)
   107  		if strings.HasSuffix(txStr, ".rlp") {
   108  			if err := decoder.Decode(&body); err != nil {
   109  				return err
   110  			}
   111  		} else {
   112  			return NewError(ErrorIO, errors.New("only rlp supported"))
   113  		}
   114  	}
   115  	signer := types.MakeSigner(chainConfig, new(big.Int))
   116  	// We now have the transactions in 'body', which is supposed to be an
   117  	// rlp list of transactions
   118  	it, err := rlp.NewListIterator([]byte(body))
   119  	if err != nil {
   120  		return err
   121  	}
   122  	var results []result
   123  	for it.Next() {
   124  		if err := it.Err(); err != nil {
   125  			return NewError(ErrorIO, err)
   126  		}
   127  		var tx types.Transaction
   128  		err := rlp.DecodeBytes(it.Value(), &tx)
   129  		if err != nil {
   130  			results = append(results, result{Error: err})
   131  			continue
   132  		}
   133  		r := result{Hash: tx.Hash()}
   134  		if sender, err := types.Sender(signer, &tx); err != nil {
   135  			r.Error = err
   136  			results = append(results, r)
   137  			continue
   138  		} else {
   139  			r.Address = sender
   140  		}
   141  		// Check intrinsic gas
   142  		if gas, err := core.IntrinsicGas(tx.Data(), tx.AccessList(), tx.To() == nil,
   143  			chainConfig.IsHomestead(new(big.Int)), chainConfig.IsIstanbul(new(big.Int))); err != nil {
   144  			r.Error = err
   145  			results = append(results, r)
   146  			continue
   147  		} else {
   148  			r.IntrinsicGas = gas
   149  			if tx.Gas() < gas {
   150  				r.Error = fmt.Errorf("%w: have %d, want %d", core.ErrIntrinsicGas, tx.Gas(), gas)
   151  				results = append(results, r)
   152  				continue
   153  			}
   154  		}
   155  		// Validate <256bit fields
   156  		switch {
   157  		case tx.Nonce()+1 < tx.Nonce():
   158  			r.Error = errors.New("nonce exceeds 2^64-1")
   159  		case tx.Value().BitLen() > 256:
   160  			r.Error = errors.New("value exceeds 256 bits")
   161  		case tx.GasPrice().BitLen() > 256:
   162  			r.Error = errors.New("gasPrice exceeds 256 bits")
   163  		case tx.GasTipCap().BitLen() > 256:
   164  			r.Error = errors.New("maxPriorityFeePerGas exceeds 256 bits")
   165  		case tx.GasFeeCap().BitLen() > 256:
   166  			r.Error = errors.New("maxFeePerGas exceeds 256 bits")
   167  		case tx.GasFeeCap().Cmp(tx.GasTipCap()) < 0:
   168  			r.Error = errors.New("maxFeePerGas < maxPriorityFeePerGas")
   169  		case new(big.Int).Mul(tx.GasPrice(), new(big.Int).SetUint64(tx.Gas())).BitLen() > 256:
   170  			r.Error = errors.New("gas * gasPrice exceeds 256 bits")
   171  		case new(big.Int).Mul(tx.GasFeeCap(), new(big.Int).SetUint64(tx.Gas())).BitLen() > 256:
   172  			r.Error = errors.New("gas * maxFeePerGas exceeds 256 bits")
   173  		}
   174  		results = append(results, r)
   175  	}
   176  	out, err := json.MarshalIndent(results, "", "  ")
   177  	fmt.Println(string(out))
   178  	return err
   179  }