github.com/coltonfike/e2c@v21.1.0+incompatible/core/types/transaction.go (about)

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser 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  // The go-ethereum library 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 Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package types
    18  
    19  import (
    20  	"container/heap"
    21  	"errors"
    22  	"fmt"
    23  	"io"
    24  	"math/big"
    25  	"sync/atomic"
    26  
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/common/hexutil"
    29  	"github.com/ethereum/go-ethereum/crypto"
    30  	"github.com/ethereum/go-ethereum/log"
    31  	"github.com/ethereum/go-ethereum/private/engine"
    32  	"github.com/ethereum/go-ethereum/rlp"
    33  )
    34  
    35  //go:generate gencodec -type txdata -field-override txdataMarshaling -out gen_tx_json.go
    36  
    37  var (
    38  	ErrInvalidSig = errors.New("invalid transaction v, r, s values")
    39  )
    40  
    41  // deriveSigner makes a *best* guess about which signer to use.
    42  func deriveSigner(V *big.Int) Signer {
    43  	// joel: this is one of the two places we used a wrong signer to print txes
    44  	if V.Sign() != 0 && isProtectedV(V) {
    45  		return NewEIP155Signer(deriveChainId(V))
    46  	} else if isPrivate(V) {
    47  		return QuorumPrivateTxSigner{}
    48  	} else {
    49  		return HomesteadSigner{}
    50  	}
    51  }
    52  
    53  type Transaction struct {
    54  	data txdata
    55  	// caches
    56  	hash atomic.Value
    57  	size atomic.Value
    58  	from atomic.Value
    59  
    60  	privacyMetadata *PrivacyMetadata
    61  }
    62  
    63  type PrivacyMetadata struct {
    64  	PrivacyFlag engine.PrivacyFlagType
    65  }
    66  
    67  type txdata struct {
    68  	AccountNonce uint64          `json:"nonce"    gencodec:"required"`
    69  	Price        *big.Int        `json:"gasPrice" gencodec:"required"`
    70  	GasLimit     uint64          `json:"gas"      gencodec:"required"`
    71  	Recipient    *common.Address `json:"to"       rlp:"nil"` // nil means contract creation
    72  	Amount       *big.Int        `json:"value"    gencodec:"required"`
    73  	Payload      []byte          `json:"input"    gencodec:"required"`
    74  
    75  	// Signature values
    76  	V *big.Int `json:"v" gencodec:"required"`
    77  	R *big.Int `json:"r" gencodec:"required"`
    78  	S *big.Int `json:"s" gencodec:"required"`
    79  
    80  	// This is only used when marshaling to JSON.
    81  	Hash *common.Hash `json:"hash" rlp:"-"`
    82  }
    83  
    84  type txdataMarshaling struct {
    85  	AccountNonce hexutil.Uint64
    86  	Price        *hexutil.Big
    87  	GasLimit     hexutil.Uint64
    88  	Amount       *hexutil.Big
    89  	Payload      hexutil.Bytes
    90  	V            *hexutil.Big
    91  	R            *hexutil.Big
    92  	S            *hexutil.Big
    93  }
    94  
    95  func NewTransaction(nonce uint64, to common.Address, amount *big.Int, gasLimit uint64, gasPrice *big.Int, data []byte) *Transaction {
    96  	return newTransaction(nonce, &to, amount, gasLimit, gasPrice, data)
    97  }
    98  
    99  func NewContractCreation(nonce uint64, amount *big.Int, gasLimit uint64, gasPrice *big.Int, data []byte) *Transaction {
   100  	return newTransaction(nonce, nil, amount, gasLimit, gasPrice, data)
   101  }
   102  
   103  func newTransaction(nonce uint64, to *common.Address, amount *big.Int, gasLimit uint64, gasPrice *big.Int, data []byte) *Transaction {
   104  	if len(data) > 0 {
   105  		data = common.CopyBytes(data)
   106  	}
   107  	d := txdata{
   108  		AccountNonce: nonce,
   109  		Recipient:    to,
   110  		Payload:      data,
   111  		Amount:       new(big.Int),
   112  		GasLimit:     gasLimit,
   113  		Price:        new(big.Int),
   114  		V:            new(big.Int),
   115  		R:            new(big.Int),
   116  		S:            new(big.Int),
   117  	}
   118  	if amount != nil {
   119  		d.Amount.Set(amount)
   120  	}
   121  	if gasPrice != nil {
   122  		d.Price.Set(gasPrice)
   123  	}
   124  
   125  	return &Transaction{data: d}
   126  }
   127  
   128  func NewTxPrivacyMetadata(privacyFlag engine.PrivacyFlagType) *PrivacyMetadata {
   129  	return &PrivacyMetadata{
   130  		PrivacyFlag: privacyFlag,
   131  	}
   132  }
   133  
   134  func (tx *Transaction) SetTxPrivacyMetadata(pm *PrivacyMetadata) {
   135  	tx.privacyMetadata = pm
   136  }
   137  
   138  // ChainId returns which chain id this transaction was signed for (if at all)
   139  func (tx *Transaction) ChainId() *big.Int {
   140  	return deriveChainId(tx.data.V)
   141  }
   142  
   143  // Protected returns whether the transaction is protected from replay protection.
   144  func (tx *Transaction) Protected() bool {
   145  	return isProtectedV(tx.data.V)
   146  }
   147  
   148  func isProtectedV(V *big.Int) bool {
   149  	if V.BitLen() <= 8 {
   150  		v := V.Uint64()
   151  		// 27 / 28 are pre eip 155 -- ie unprotected.
   152  		return !(v == 27 || v == 28)
   153  	}
   154  	// anything not 27 or 28 is considered protected
   155  	return true
   156  }
   157  
   158  // EncodeRLP implements rlp.Encoder
   159  func (tx *Transaction) EncodeRLP(w io.Writer) error {
   160  	return rlp.Encode(w, &tx.data)
   161  }
   162  
   163  // DecodeRLP implements rlp.Decoder
   164  func (tx *Transaction) DecodeRLP(s *rlp.Stream) error {
   165  	_, size, _ := s.Kind()
   166  	err := s.Decode(&tx.data)
   167  	if err == nil {
   168  		tx.size.Store(common.StorageSize(rlp.ListSize(size)))
   169  	}
   170  
   171  	return err
   172  }
   173  
   174  // MarshalJSON encodes the web3 RPC transaction format.
   175  func (tx *Transaction) MarshalJSON() ([]byte, error) {
   176  	hash := tx.Hash()
   177  	data := tx.data
   178  	data.Hash = &hash
   179  	return data.MarshalJSON()
   180  }
   181  
   182  // UnmarshalJSON decodes the web3 RPC transaction format.
   183  func (tx *Transaction) UnmarshalJSON(input []byte) error {
   184  	var dec txdata
   185  	if err := dec.UnmarshalJSON(input); err != nil {
   186  		return err
   187  	}
   188  
   189  	withSignature := dec.V.Sign() != 0 || dec.R.Sign() != 0 || dec.S.Sign() != 0
   190  	if withSignature {
   191  		var V byte
   192  		if isProtectedV(dec.V) {
   193  			chainID := deriveChainId(dec.V).Uint64()
   194  			V = byte(dec.V.Uint64() - 35 - 2*chainID)
   195  		} else {
   196  			V = byte(dec.V.Uint64() - 27)
   197  		}
   198  		if !crypto.ValidateSignatureValues(V, dec.R, dec.S, false) {
   199  			return ErrInvalidSig
   200  		}
   201  	}
   202  
   203  	*tx = Transaction{data: dec}
   204  	return nil
   205  }
   206  
   207  func (tx *Transaction) Data() []byte                      { return common.CopyBytes(tx.data.Payload) }
   208  func (tx *Transaction) Gas() uint64                       { return tx.data.GasLimit }
   209  func (tx *Transaction) GasPrice() *big.Int                { return new(big.Int).Set(tx.data.Price) }
   210  func (tx *Transaction) Value() *big.Int                   { return new(big.Int).Set(tx.data.Amount) }
   211  func (tx *Transaction) Nonce() uint64                     { return tx.data.AccountNonce }
   212  func (tx *Transaction) CheckNonce() bool                  { return true }
   213  func (tx *Transaction) PrivacyMetadata() *PrivacyMetadata { return tx.privacyMetadata }
   214  
   215  // To returns the recipient address of the transaction.
   216  // It returns nil if the transaction is a contract creation.
   217  func (tx *Transaction) To() *common.Address {
   218  	if tx.data.Recipient == nil {
   219  		return nil
   220  	}
   221  	to := *tx.data.Recipient
   222  	return &to
   223  }
   224  
   225  func (tx *Transaction) From() common.Address {
   226  	signer := deriveSigner(tx.data.V)
   227  	if from, err := Sender(signer, tx); err == nil {
   228  		return from
   229  	}
   230  	return common.Address{}
   231  }
   232  
   233  // Hash hashes the RLP encoding of tx.
   234  // It uniquely identifies the transaction.
   235  func (tx *Transaction) Hash() common.Hash {
   236  	if hash := tx.hash.Load(); hash != nil {
   237  		return hash.(common.Hash)
   238  	}
   239  	v := rlpHash(tx)
   240  	tx.hash.Store(v)
   241  	return v
   242  }
   243  
   244  // Size returns the true RLP encoded storage size of the transaction, either by
   245  // encoding and returning it, or returning a previsouly cached value.
   246  func (tx *Transaction) Size() common.StorageSize {
   247  	if size := tx.size.Load(); size != nil {
   248  		return size.(common.StorageSize)
   249  	}
   250  	c := writeCounter(0)
   251  	rlp.Encode(&c, &tx.data)
   252  	tx.size.Store(common.StorageSize(c))
   253  	return common.StorageSize(c)
   254  }
   255  
   256  // AsMessage returns the transaction as a core.Message.
   257  //
   258  // AsMessage requires a signer to derive the sender.
   259  //
   260  // XXX Rename message to something less arbitrary?
   261  func (tx *Transaction) AsMessage(s Signer) (Message, error) {
   262  	msg := Message{
   263  		nonce:      tx.data.AccountNonce,
   264  		gasLimit:   tx.data.GasLimit,
   265  		gasPrice:   new(big.Int).Set(tx.data.Price),
   266  		to:         tx.data.Recipient,
   267  		amount:     tx.data.Amount,
   268  		data:       tx.data.Payload,
   269  		checkNonce: true,
   270  		isPrivate:  tx.IsPrivate(),
   271  	}
   272  
   273  	var err error
   274  	msg.from, err = Sender(s, tx)
   275  	return msg, err
   276  }
   277  
   278  // WithSignature returns a new transaction with the given signature.
   279  // This signature needs to be in the [R || S || V] format where V is 0 or 1.
   280  func (tx *Transaction) WithSignature(signer Signer, sig []byte) (*Transaction, error) {
   281  	r, s, v, err := signer.SignatureValues(tx, sig)
   282  	if err != nil {
   283  		return nil, err
   284  	}
   285  	cpy := &Transaction{data: tx.data}
   286  	cpy.data.R, cpy.data.S, cpy.data.V = r, s, v
   287  	return cpy, nil
   288  }
   289  
   290  // Cost returns amount + gasprice * gaslimit.
   291  func (tx *Transaction) Cost() *big.Int {
   292  	total := new(big.Int).Mul(tx.data.Price, new(big.Int).SetUint64(tx.data.GasLimit))
   293  	total.Add(total, tx.data.Amount)
   294  	return total
   295  }
   296  
   297  // RawSignatureValues returns the V, R, S signature values of the transaction.
   298  // The return values should not be modified by the caller.
   299  func (tx *Transaction) RawSignatureValues() (v, r, s *big.Int) {
   300  	return tx.data.V, tx.data.R, tx.data.S
   301  }
   302  
   303  func (tx *Transaction) String() string {
   304  	var from, to string
   305  	if tx.data.V != nil {
   306  		// make a best guess about the signer and use that to derive
   307  		// the sender.
   308  		signer := deriveSigner(tx.data.V)
   309  		if f, err := Sender(signer, tx); err != nil { // derive but don't cache
   310  			from = "[invalid sender: invalid sig]"
   311  		} else {
   312  			from = fmt.Sprintf("%x", f[:])
   313  		}
   314  	} else {
   315  		from = "[invalid sender: nil V field]"
   316  	}
   317  
   318  	if tx.data.Recipient == nil {
   319  		to = "[contract creation]"
   320  	} else {
   321  		to = fmt.Sprintf("%x", tx.data.Recipient[:])
   322  	}
   323  	enc, _ := rlp.EncodeToBytes(&tx.data)
   324  	return fmt.Sprintf(`
   325  	TX(%x)
   326  	Contract: %v
   327  	From:     %s
   328  	To:       %s
   329  	Nonce:    %v
   330  	GasPrice: %#x
   331  	GasLimit  %#x
   332  	Value:    %#x
   333  	Data:     0x%x
   334  	V:        %#x
   335  	R:        %#x
   336  	S:        %#x
   337  	Hex:      %x
   338  `,
   339  		tx.Hash(),
   340  		tx.data.Recipient == nil,
   341  		from,
   342  		to,
   343  		tx.data.AccountNonce,
   344  		tx.data.Price,
   345  		tx.data.GasLimit,
   346  		tx.data.Amount,
   347  		tx.data.Payload,
   348  		tx.data.V,
   349  		tx.data.R,
   350  		tx.data.S,
   351  		enc,
   352  	)
   353  }
   354  
   355  // Transactions is a Transaction slice type for basic sorting.
   356  type Transactions []*Transaction
   357  
   358  // Len returns the length of s.
   359  func (s Transactions) Len() int { return len(s) }
   360  
   361  // Swap swaps the i'th and the j'th element in s.
   362  func (s Transactions) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
   363  
   364  // GetRlp implements Rlpable and returns the i'th element of s in rlp.
   365  func (s Transactions) GetRlp(i int) []byte {
   366  	enc, _ := rlp.EncodeToBytes(s[i])
   367  	return enc
   368  }
   369  
   370  // TxDifference returns a new set which is the difference between a and b.
   371  func TxDifference(a, b Transactions) Transactions {
   372  	keep := make(Transactions, 0, len(a))
   373  
   374  	remove := make(map[common.Hash]struct{})
   375  	for _, tx := range b {
   376  		remove[tx.Hash()] = struct{}{}
   377  	}
   378  
   379  	for _, tx := range a {
   380  		if _, ok := remove[tx.Hash()]; !ok {
   381  			keep = append(keep, tx)
   382  		}
   383  	}
   384  
   385  	return keep
   386  }
   387  
   388  // TxByNonce implements the sort interface to allow sorting a list of transactions
   389  // by their nonces. This is usually only useful for sorting transactions from a
   390  // single account, otherwise a nonce comparison doesn't make much sense.
   391  type TxByNonce Transactions
   392  
   393  func (s TxByNonce) Len() int           { return len(s) }
   394  func (s TxByNonce) Less(i, j int) bool { return s[i].data.AccountNonce < s[j].data.AccountNonce }
   395  func (s TxByNonce) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
   396  
   397  // TxByPrice implements both the sort and the heap interface, making it useful
   398  // for all at once sorting as well as individually adding and removing elements.
   399  type TxByPrice Transactions
   400  
   401  func (s TxByPrice) Len() int           { return len(s) }
   402  func (s TxByPrice) Less(i, j int) bool { return s[i].data.Price.Cmp(s[j].data.Price) > 0 }
   403  func (s TxByPrice) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
   404  
   405  func (s *TxByPrice) Push(x interface{}) {
   406  	*s = append(*s, x.(*Transaction))
   407  }
   408  
   409  func (s *TxByPrice) Pop() interface{} {
   410  	old := *s
   411  	n := len(old)
   412  	x := old[n-1]
   413  	*s = old[0 : n-1]
   414  	return x
   415  }
   416  
   417  // TransactionsByPriceAndNonce represents a set of transactions that can return
   418  // transactions in a profit-maximizing sorted order, while supporting removing
   419  // entire batches of transactions for non-executable accounts.
   420  type TransactionsByPriceAndNonce struct {
   421  	txs    map[common.Address]Transactions // Per account nonce-sorted list of transactions
   422  	heads  TxByPrice                       // Next transaction for each unique account (price heap)
   423  	signer Signer                          // Signer for the set of transactions
   424  }
   425  
   426  // NewTransactionsByPriceAndNonce creates a transaction set that can retrieve
   427  // price sorted transactions in a nonce-honouring way.
   428  //
   429  // Note, the input map is reowned so the caller should not interact any more with
   430  // if after providing it to the constructor.
   431  func NewTransactionsByPriceAndNonce(signer Signer, txs map[common.Address]Transactions) *TransactionsByPriceAndNonce {
   432  	// Initialize a price based heap with the head transactions
   433  	heads := make(TxByPrice, 0, len(txs))
   434  	for from, accTxs := range txs {
   435  		// Ensure the sender address is from the signer
   436  		acc, err := Sender(signer, accTxs[0])
   437  		if err == nil {
   438  			heads = append(heads, accTxs[0])
   439  			txs[acc] = accTxs[1:]
   440  		} else {
   441  			log.Info("Failed to recovered sender address, this transaction is skipped", "from", from, "nonce", accTxs[0].data.AccountNonce, "err", err)
   442  		}
   443  		if from != acc {
   444  			delete(txs, from)
   445  		}
   446  	}
   447  	heap.Init(&heads)
   448  
   449  	// Assemble and return the transaction set
   450  	return &TransactionsByPriceAndNonce{
   451  		txs:    txs,
   452  		heads:  heads,
   453  		signer: signer,
   454  	}
   455  }
   456  
   457  // Peek returns the next transaction by price.
   458  func (t *TransactionsByPriceAndNonce) Peek() *Transaction {
   459  	if len(t.heads) == 0 {
   460  		return nil
   461  	}
   462  	return t.heads[0]
   463  }
   464  
   465  // Shift replaces the current best head with the next one from the same account.
   466  func (t *TransactionsByPriceAndNonce) Shift() {
   467  	acc, _ := Sender(t.signer, t.heads[0])
   468  	if txs, ok := t.txs[acc]; ok && len(txs) > 0 {
   469  		t.heads[0], t.txs[acc] = txs[0], txs[1:]
   470  		heap.Fix(&t.heads, 0)
   471  	} else {
   472  		heap.Pop(&t.heads)
   473  	}
   474  }
   475  
   476  // Pop removes the best transaction, *not* replacing it with the next one from
   477  // the same account. This should be used when a transaction cannot be executed
   478  // and hence all subsequent ones should be discarded from the same account.
   479  func (t *TransactionsByPriceAndNonce) Pop() {
   480  	heap.Pop(&t.heads)
   481  }
   482  
   483  // Message is a fully derived transaction and implements core.Message
   484  //
   485  // NOTE: In a future PR this will be removed.
   486  type Message struct {
   487  	to         *common.Address
   488  	from       common.Address
   489  	nonce      uint64
   490  	amount     *big.Int
   491  	gasLimit   uint64
   492  	gasPrice   *big.Int
   493  	data       []byte
   494  	checkNonce bool
   495  	isPrivate  bool
   496  }
   497  
   498  func NewMessage(from common.Address, to *common.Address, nonce uint64, amount *big.Int, gasLimit uint64, gasPrice *big.Int, data []byte, checkNonce bool) Message {
   499  	return Message{
   500  		from:       from,
   501  		to:         to,
   502  		nonce:      nonce,
   503  		amount:     amount,
   504  		gasLimit:   gasLimit,
   505  		gasPrice:   gasPrice,
   506  		data:       data,
   507  		checkNonce: checkNonce,
   508  	}
   509  }
   510  
   511  func (m Message) From() common.Address { return m.from }
   512  func (m Message) To() *common.Address  { return m.to }
   513  func (m Message) GasPrice() *big.Int   { return m.gasPrice }
   514  func (m Message) Value() *big.Int      { return m.amount }
   515  func (m Message) Gas() uint64          { return m.gasLimit }
   516  func (m Message) Nonce() uint64        { return m.nonce }
   517  func (m Message) Data() []byte         { return m.data }
   518  func (m Message) CheckNonce() bool     { return m.checkNonce }
   519  
   520  func (m Message) IsPrivate() bool {
   521  	return m.isPrivate
   522  }
   523  
   524  func (tx *Transaction) IsPrivate() bool {
   525  	if tx.data.V == nil {
   526  		return false
   527  	}
   528  	return tx.data.V.Uint64() == 37 || tx.data.V.Uint64() == 38
   529  }
   530  
   531  /*
   532   * Indicates that a transaction is private, but doesn't necessarily set the correct v value, as it can be called on
   533   * an unsigned transaction.
   534   * pre homestead signer, all v values were v=27 or v=28, with EIP155Signer that change,
   535   * but SetPrivate() is also used on unsigned transactions to temporarily set the v value to indicate
   536   * the transaction is intended to be private, and so that the correct signer can be selected. The signer will correctly
   537   * set the valid v value (37 or 38): This helps minimize changes vs upstream go-ethereum code.
   538   */
   539  func (tx *Transaction) SetPrivate() {
   540  	if tx.IsPrivate() {
   541  		return
   542  	}
   543  	if tx.data.V.Int64() == 28 {
   544  		tx.data.V.SetUint64(38)
   545  	} else {
   546  		tx.data.V.SetUint64(37)
   547  	}
   548  }