github.com/codingfuture/orig-energi3@v0.8.4/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.Error(err)
    93  		t.FailNow()
    94  	}
    95  
    96  	from, err := Sender(HomesteadSigner{}, tx)
    97  	if err != nil {
    98  		t.Error(err)
    99  		t.FailNow()
   100  	}
   101  	if addr != from {
   102  		t.Error("derived address doesn't match")
   103  	}
   104  }
   105  
   106  func TestRecipientNormal(t *testing.T) {
   107  	_, addr := defaultTestKey()
   108  
   109  	tx, err := decodeTx(common.Hex2Bytes("f85d80808094000000000000000000000000000000000000000080011ca0527c0d8f5c63f7b9f41324a7c8a563ee1190bcbf0dac8ab446291bdbf32f5c79a0552c4ef0a09a04395074dab9ed34d3fbfb843c2f2546cc30fe89ec143ca94ca6"))
   110  	if err != nil {
   111  		t.Error(err)
   112  		t.FailNow()
   113  	}
   114  
   115  	from, err := Sender(HomesteadSigner{}, tx)
   116  	if err != nil {
   117  		t.Error(err)
   118  		t.FailNow()
   119  	}
   120  
   121  	if addr != from {
   122  		t.Error("derived address doesn't match")
   123  	}
   124  }
   125  
   126  // Tests that transactions can be correctly sorted according to their price in
   127  // decreasing order, but at the same time with increasing nonces when issued by
   128  // the same account.
   129  func TestTransactionPriceNonceSort(t *testing.T) {
   130  	// Generate a batch of accounts to start with
   131  	keys := make([]*ecdsa.PrivateKey, 25)
   132  	for i := 0; i < len(keys); i++ {
   133  		keys[i], _ = crypto.GenerateKey()
   134  	}
   135  
   136  	signer := HomesteadSigner{}
   137  	// Generate a batch of transactions with overlapping values, but shifted nonces
   138  	groups := map[common.Address]Transactions{}
   139  	for start, key := range keys {
   140  		addr := crypto.PubkeyToAddress(key.PublicKey)
   141  		for i := 0; i < 25; i++ {
   142  			tx, _ := SignTx(NewTransaction(uint64(start+i), common.Address{}, big.NewInt(100), 100, big.NewInt(int64(start+i)), nil), signer, key)
   143  			groups[addr] = append(groups[addr], tx)
   144  		}
   145  	}
   146  	// Sort the transactions and cross check the nonce ordering
   147  	txset := NewTransactionsByPriceAndNonce(signer, groups)
   148  
   149  	txs := Transactions{}
   150  	for tx := txset.Peek(); tx != nil; tx = txset.Peek() {
   151  		txs = append(txs, tx)
   152  		txset.Shift()
   153  	}
   154  	if len(txs) != 25*25 {
   155  		t.Errorf("expected %d transactions, found %d", 25*25, len(txs))
   156  	}
   157  	for i, txi := range txs {
   158  		fromi, _ := Sender(signer, txi)
   159  
   160  		// Make sure the nonce order is valid
   161  		for j, txj := range txs[i+1:] {
   162  			fromj, _ := Sender(signer, txj)
   163  
   164  			if fromi == fromj && txi.Nonce() > txj.Nonce() {
   165  				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())
   166  			}
   167  		}
   168  
   169  		// If the next tx has different from account, the price must be lower than the current one
   170  		if i+1 < len(txs) {
   171  			next := txs[i+1]
   172  			fromNext, _ := Sender(signer, next)
   173  			if fromi != fromNext && txi.GasPrice().Cmp(next.GasPrice()) < 0 {
   174  				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())
   175  			}
   176  		}
   177  	}
   178  }
   179  
   180  // TestTransactionJSON tests serializing/de-serializing to/from JSON.
   181  func TestTransactionJSON(t *testing.T) {
   182  	key, err := crypto.GenerateKey()
   183  	if err != nil {
   184  		t.Fatalf("could not generate key: %v", err)
   185  	}
   186  	signer := NewEIP155Signer(common.Big1)
   187  
   188  	transactions := make([]*Transaction, 0, 50)
   189  	for i := uint64(0); i < 25; i++ {
   190  		var tx *Transaction
   191  		switch i % 2 {
   192  		case 0:
   193  			tx = NewTransaction(i, common.Address{1}, common.Big0, 1, common.Big2, []byte("abcdef"))
   194  		case 1:
   195  			tx = NewContractCreation(i, common.Big0, 1, common.Big2, []byte("abcdef"))
   196  		}
   197  		transactions = append(transactions, tx)
   198  
   199  		signedTx, err := SignTx(tx, signer, key)
   200  		if err != nil {
   201  			t.Fatalf("could not sign transaction: %v", err)
   202  		}
   203  
   204  		transactions = append(transactions, signedTx)
   205  	}
   206  
   207  	for _, tx := range transactions {
   208  		data, err := json.Marshal(tx)
   209  		if err != nil {
   210  			t.Fatalf("json.Marshal failed: %v", err)
   211  		}
   212  
   213  		var parsedTx *Transaction
   214  		if err := json.Unmarshal(data, &parsedTx); err != nil {
   215  			t.Fatalf("json.Unmarshal failed: %v", err)
   216  		}
   217  
   218  		// compare nonce, price, gaslimit, recipient, amount, payload, V, R, S
   219  		if tx.Hash() != parsedTx.Hash() {
   220  			t.Errorf("parsed tx differs from original tx, want %v, got %v", tx, parsedTx)
   221  		}
   222  		if tx.ChainId().Cmp(parsedTx.ChainId()) != 0 {
   223  			t.Errorf("invalid chain id, want %d, got %d", tx.ChainId(), parsedTx.ChainId())
   224  		}
   225  	}
   226  }