github.com/AlohaMobile/go-ethereum@v1.9.7/core/types/transaction_test.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  	"bytes"
    21  	"crypto/ecdsa"
    22  	"encoding/json"
    23  	"math/big"
    24  	"testing"
    25  
    26  	"github.com/ethereum/go-ethereum/common"
    27  	"github.com/ethereum/go-ethereum/crypto"
    28  	"github.com/ethereum/go-ethereum/rlp"
    29  )
    30  
    31  // The values in those tests are from the Transaction Tests
    32  // at github.com/ethereum/tests.
    33  var (
    34  	emptyTx = NewTransaction(
    35  		0,
    36  		common.HexToAddress("095e7baea6a6c7c4c2dfeb977efac326af552d87"),
    37  		big.NewInt(0), 0, big.NewInt(0),
    38  		nil,
    39  	)
    40  
    41  	rightvrsTx, _ = NewTransaction(
    42  		3,
    43  		common.HexToAddress("b94f5374fce5edbc8e2a8697c15331677e6ebf0b"),
    44  		big.NewInt(10),
    45  		2000,
    46  		big.NewInt(1),
    47  		common.FromHex("5544"),
    48  	).WithSignature(
    49  		HomesteadSigner{},
    50  		common.Hex2Bytes("98ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4a8887321be575c8095f789dd4c743dfe42c1820f9231f98a962b210e3ac2452a301"),
    51  	)
    52  )
    53  
    54  func TestTransactionSigHash(t *testing.T) {
    55  	var homestead HomesteadSigner
    56  	if homestead.Hash(emptyTx) != common.HexToHash("c775b99e7ad12f50d819fcd602390467e28141316969f4b57f0626f74fe3b386") {
    57  		t.Errorf("empty transaction hash mismatch, got %x", emptyTx.Hash())
    58  	}
    59  	if homestead.Hash(rightvrsTx) != common.HexToHash("fe7a79529ed5f7c3375d06b26b186a8644e0e16c373d7a12be41c62d6042b77a") {
    60  		t.Errorf("RightVRS transaction hash mismatch, got %x", rightvrsTx.Hash())
    61  	}
    62  }
    63  
    64  func TestTransactionEncode(t *testing.T) {
    65  	txb, err := rlp.EncodeToBytes(rightvrsTx)
    66  	if err != nil {
    67  		t.Fatalf("encode error: %v", err)
    68  	}
    69  	should := common.FromHex("f86103018207d094b94f5374fce5edbc8e2a8697c15331677e6ebf0b0a8255441ca098ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4aa08887321be575c8095f789dd4c743dfe42c1820f9231f98a962b210e3ac2452a3")
    70  	if !bytes.Equal(txb, should) {
    71  		t.Errorf("encoded RLP mismatch, got %x", txb)
    72  	}
    73  }
    74  
    75  func decodeTx(data []byte) (*Transaction, error) {
    76  	var tx Transaction
    77  	t, err := &tx, rlp.Decode(bytes.NewReader(data), &tx)
    78  
    79  	return t, err
    80  }
    81  
    82  func defaultTestKey() (*ecdsa.PrivateKey, common.Address) {
    83  	key, _ := crypto.HexToECDSA("45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8")
    84  	addr := crypto.PubkeyToAddress(key.PublicKey)
    85  	return key, addr
    86  }
    87  
    88  func TestRecipientEmpty(t *testing.T) {
    89  	_, addr := defaultTestKey()
    90  	tx, err := decodeTx(common.Hex2Bytes("f8498080808080011ca09b16de9d5bdee2cf56c28d16275a4da68cd30273e2525f3959f5d62557489921a0372ebd8fb3345f7db7b5a86d42e24d36e983e259b0664ceb8c227ec9af572f3d"))
    91  	if err != nil {
    92  		t.Fatal(err)
    93  	}
    94  
    95  	from, err := Sender(HomesteadSigner{}, tx)
    96  	if err != nil {
    97  		t.Fatal(err)
    98  	}
    99  	if addr != from {
   100  		t.Fatal("derived address doesn't match")
   101  	}
   102  }
   103  
   104  func TestRecipientNormal(t *testing.T) {
   105  	_, addr := defaultTestKey()
   106  
   107  	tx, err := decodeTx(common.Hex2Bytes("f85d80808094000000000000000000000000000000000000000080011ca0527c0d8f5c63f7b9f41324a7c8a563ee1190bcbf0dac8ab446291bdbf32f5c79a0552c4ef0a09a04395074dab9ed34d3fbfb843c2f2546cc30fe89ec143ca94ca6"))
   108  	if err != nil {
   109  		t.Fatal(err)
   110  	}
   111  
   112  	from, err := Sender(HomesteadSigner{}, tx)
   113  	if err != nil {
   114  		t.Fatal(err)
   115  	}
   116  	if addr != from {
   117  		t.Fatal("derived address doesn't match")
   118  	}
   119  }
   120  
   121  // Tests that transactions can be correctly sorted according to their price in
   122  // decreasing order, but at the same time with increasing nonces when issued by
   123  // the same account.
   124  func TestTransactionPriceNonceSort(t *testing.T) {
   125  	// Generate a batch of accounts to start with
   126  	keys := make([]*ecdsa.PrivateKey, 25)
   127  	for i := 0; i < len(keys); i++ {
   128  		keys[i], _ = crypto.GenerateKey()
   129  	}
   130  
   131  	signer := HomesteadSigner{}
   132  	// Generate a batch of transactions with overlapping values, but shifted nonces
   133  	groups := map[common.Address]Transactions{}
   134  	for start, key := range keys {
   135  		addr := crypto.PubkeyToAddress(key.PublicKey)
   136  		for i := 0; i < 25; i++ {
   137  			tx, _ := SignTx(NewTransaction(uint64(start+i), common.Address{}, big.NewInt(100), 100, big.NewInt(int64(start+i)), nil), signer, key)
   138  			groups[addr] = append(groups[addr], tx)
   139  		}
   140  	}
   141  	// Sort the transactions and cross check the nonce ordering
   142  	txset := NewTransactionsByPriceAndNonce(signer, groups)
   143  
   144  	txs := Transactions{}
   145  	for tx := txset.Peek(); tx != nil; tx = txset.Peek() {
   146  		txs = append(txs, tx)
   147  		txset.Shift()
   148  	}
   149  	if len(txs) != 25*25 {
   150  		t.Errorf("expected %d transactions, found %d", 25*25, len(txs))
   151  	}
   152  	for i, txi := range txs {
   153  		fromi, _ := Sender(signer, txi)
   154  
   155  		// Make sure the nonce order is valid
   156  		for j, txj := range txs[i+1:] {
   157  			fromj, _ := Sender(signer, txj)
   158  
   159  			if fromi == fromj && txi.Nonce() > txj.Nonce() {
   160  				t.Errorf("invalid nonce ordering: tx #%d (A=%x N=%v) < tx #%d (A=%x N=%v)", i, fromi[:4], txi.Nonce(), i+j, fromj[:4], txj.Nonce())
   161  			}
   162  		}
   163  
   164  		// If the next tx has different from account, the price must be lower than the current one
   165  		if i+1 < len(txs) {
   166  			next := txs[i+1]
   167  			fromNext, _ := Sender(signer, next)
   168  			if fromi != fromNext && txi.GasPrice().Cmp(next.GasPrice()) < 0 {
   169  				t.Errorf("invalid gasprice ordering: tx #%d (A=%x P=%v) < tx #%d (A=%x P=%v)", i, fromi[:4], txi.GasPrice(), i+1, fromNext[:4], next.GasPrice())
   170  			}
   171  		}
   172  	}
   173  }
   174  
   175  // TestTransactionJSON tests serializing/de-serializing to/from JSON.
   176  func TestTransactionJSON(t *testing.T) {
   177  	key, err := crypto.GenerateKey()
   178  	if err != nil {
   179  		t.Fatalf("could not generate key: %v", err)
   180  	}
   181  	signer := NewEIP155Signer(common.Big1)
   182  
   183  	transactions := make([]*Transaction, 0, 50)
   184  	for i := uint64(0); i < 25; i++ {
   185  		var tx *Transaction
   186  		switch i % 2 {
   187  		case 0:
   188  			tx = NewTransaction(i, common.Address{1}, common.Big0, 1, common.Big2, []byte("abcdef"))
   189  		case 1:
   190  			tx = NewContractCreation(i, common.Big0, 1, common.Big2, []byte("abcdef"))
   191  		}
   192  		transactions = append(transactions, tx)
   193  
   194  		signedTx, err := SignTx(tx, signer, key)
   195  		if err != nil {
   196  			t.Fatalf("could not sign transaction: %v", err)
   197  		}
   198  
   199  		transactions = append(transactions, signedTx)
   200  	}
   201  
   202  	for _, tx := range transactions {
   203  		data, err := json.Marshal(tx)
   204  		if err != nil {
   205  			t.Fatalf("json.Marshal failed: %v", err)
   206  		}
   207  
   208  		var parsedTx *Transaction
   209  		if err := json.Unmarshal(data, &parsedTx); err != nil {
   210  			t.Fatalf("json.Unmarshal failed: %v", err)
   211  		}
   212  
   213  		// compare nonce, price, gaslimit, recipient, amount, payload, V, R, S
   214  		if tx.Hash() != parsedTx.Hash() {
   215  			t.Errorf("parsed tx differs from original tx, want %v, got %v", tx, parsedTx)
   216  		}
   217  		if tx.ChainId().Cmp(parsedTx.ChainId()) != 0 {
   218  			t.Errorf("invalid chain id, want %d, got %d", tx.ChainId(), parsedTx.ChainId())
   219  		}
   220  	}
   221  }