github.com/klaytn/klaytn@v1.12.1/node/cn/peer_test.go (about)

     1  // Copyright 2019 The klaytn Authors
     2  // This file is part of the klaytn library.
     3  //
     4  // The klaytn 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 klaytn 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 klaytn library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package cn
    18  
    19  import (
    20  	"crypto/ecdsa"
    21  	"math/big"
    22  	"math/rand"
    23  	"sort"
    24  	"strings"
    25  	"testing"
    26  	"time"
    27  
    28  	"github.com/klaytn/klaytn/crypto"
    29  
    30  	"github.com/klaytn/klaytn/blockchain/types"
    31  	"github.com/klaytn/klaytn/common"
    32  	"github.com/klaytn/klaytn/networks/p2p"
    33  	"github.com/stretchr/testify/assert"
    34  )
    35  
    36  var version = 63
    37  
    38  func newBasePeer() (Peer, *p2p.MsgPipeRW, *p2p.MsgPipeRW) {
    39  	pipe1, pipe2 := p2p.MsgPipe()
    40  
    41  	return newPeer(version, p2pPeers[0], pipe1), pipe1, pipe2
    42  }
    43  
    44  func TestBasePeer_AddToKnownBlocks(t *testing.T) {
    45  	basePeer, _, _ := newBasePeer()
    46  	assert.False(t, basePeer.KnowsBlock(hash1))
    47  	basePeer.AddToKnownBlocks(hash1)
    48  	assert.True(t, basePeer.KnowsBlock(hash1))
    49  }
    50  
    51  func TestBasePeer_AddToKnownTxs(t *testing.T) {
    52  	basePeer, _, _ := newBasePeer()
    53  	assert.False(t, basePeer.KnowsTx(hash1))
    54  	basePeer.AddToKnownTxs(hash1)
    55  	assert.True(t, basePeer.KnowsTx(hash1))
    56  }
    57  
    58  func TestBasePeer_Send(t *testing.T) {
    59  	basePeer, _, oppositePipe := newBasePeer()
    60  	data := "a message data"
    61  	expectedMsg := generateMsg(t, NewBlockHashesMsg, data)
    62  	go func(t *testing.T) {
    63  		if err := basePeer.Send(NewBlockHashesMsg, data); err != nil {
    64  			t.Error(err)
    65  			return
    66  		}
    67  	}(t)
    68  	receivedMsg, err := oppositePipe.ReadMsg()
    69  	if err != nil {
    70  		t.Fatal(err)
    71  	}
    72  	assert.Equal(t, expectedMsg.Code, receivedMsg.Code)
    73  	assert.Equal(t, expectedMsg.Size, receivedMsg.Size)
    74  
    75  	var decodedStr string
    76  	if err := receivedMsg.Decode(&decodedStr); err != nil {
    77  		t.Fatal(err)
    78  	}
    79  	assert.Equal(t, data, decodedStr)
    80  }
    81  
    82  func TestBasePeer_SendTransactions(t *testing.T) {
    83  	sentTxs := types.Transactions{tx1}
    84  
    85  	basePeer, _, oppositePipe := newBasePeer()
    86  	assert.False(t, basePeer.KnowsTx(sentTxs[0].Hash()))
    87  	go func(t *testing.T) {
    88  		if err := basePeer.SendTransactions(sentTxs); err != nil {
    89  			t.Error(t)
    90  			return
    91  		}
    92  	}(t)
    93  	receivedMsg, err := oppositePipe.ReadMsg()
    94  	if err != nil {
    95  		t.Fatal(err)
    96  	}
    97  
    98  	var receivedTxs types.Transactions
    99  	if err := receivedMsg.Decode(&receivedTxs); err != nil {
   100  		t.Fatal(err)
   101  	}
   102  
   103  	assert.True(t, basePeer.KnowsTx(tx1.Hash()))
   104  	assert.Equal(t, len(sentTxs), len(receivedTxs))
   105  	assert.Equal(t, sentTxs[0].Hash(), receivedTxs[0].Hash())
   106  
   107  	sendTxBinary, _ := sentTxs[0].MarshalBinary()
   108  	receivedTxBinary, _ := receivedTxs[0].MarshalBinary()
   109  	assert.Equal(t, sendTxBinary, receivedTxBinary)
   110  }
   111  
   112  func TestBasePeer_ReSendTransactions(t *testing.T) {
   113  	sentTxs := types.Transactions{tx1}
   114  
   115  	basePeer, _, oppositePipe := newBasePeer()
   116  	assert.False(t, basePeer.KnowsTx(sentTxs[0].Hash()))
   117  	go func(t *testing.T) {
   118  		if err := basePeer.ReSendTransactions(sentTxs); err != nil {
   119  			t.Error(t)
   120  			return
   121  		}
   122  	}(t)
   123  	receivedMsg, err := oppositePipe.ReadMsg()
   124  	if err != nil {
   125  		t.Fatal(err)
   126  	}
   127  
   128  	var receivedTxs types.Transactions
   129  	if err := receivedMsg.Decode(&receivedTxs); err != nil {
   130  		t.Fatal(err)
   131  	}
   132  
   133  	assert.False(t, basePeer.KnowsTx(tx1.Hash()))
   134  	assert.Equal(t, len(sentTxs), len(receivedTxs))
   135  	assert.Equal(t, sentTxs[0].Hash(), receivedTxs[0].Hash())
   136  
   137  	sendTxBinary, _ := sentTxs[0].MarshalBinary()
   138  	receivedTxBinary, _ := receivedTxs[0].MarshalBinary()
   139  	assert.Equal(t, sendTxBinary, receivedTxBinary)
   140  }
   141  
   142  func TestBasePeer_AsyncSendTransactions(t *testing.T) {
   143  	sentTxs := types.Transactions{tx1}
   144  	lastTxs := types.Transactions{types.NewTransaction(333, addrs[0], big.NewInt(333), 333, big.NewInt(333), addrs[0][:])}
   145  
   146  	basePeer, _, _ := newBasePeer()
   147  
   148  	// To queuedTxs be filled with transactions
   149  	for i := 0; i < maxQueuedTxs; i++ {
   150  		basePeer.AsyncSendTransactions(sentTxs)
   151  	}
   152  	// lastTxs shouldn't go into the queuedTxs
   153  	basePeer.AsyncSendTransactions(lastTxs)
   154  
   155  	assert.True(t, basePeer.KnowsTx(tx1.Hash()))
   156  	assert.False(t, basePeer.KnowsTx(lastTxs[0].Hash()))
   157  }
   158  
   159  func TestBasePeer_ConnType(t *testing.T) {
   160  	basePeer, _, _ := newBasePeer()
   161  	assert.Equal(t, common.CONSENSUSNODE, basePeer.ConnType())
   162  }
   163  
   164  func TestBasePeer_GetAndSetAddr(t *testing.T) {
   165  	basePeer, _, _ := newBasePeer()
   166  	assert.Equal(t, common.Address{}, basePeer.GetAddr())
   167  	basePeer.SetAddr(addrs[0])
   168  	assert.Equal(t, addrs[0], basePeer.GetAddr())
   169  	basePeer.SetAddr(addrs[1])
   170  	assert.Equal(t, addrs[1], basePeer.GetAddr())
   171  }
   172  
   173  func TestBasePeer_GetVersion(t *testing.T) {
   174  	basePeer, _, _ := newBasePeer()
   175  	assert.Equal(t, version, basePeer.GetVersion())
   176  }
   177  
   178  func TestBasePeer_RegisterConsensusMsgCode(t *testing.T) {
   179  	basePeer, _, _ := newBasePeer()
   180  	assert.True(t, strings.Contains(basePeer.RegisterConsensusMsgCode(NewBlockHashesMsg).Error(), errNotSupportedByBasePeer.Error()))
   181  }
   182  
   183  func TestBasePeer_GetRW(t *testing.T) {
   184  	basePeer, pipe1, _ := newBasePeer()
   185  	assert.Equal(t, pipe1, basePeer.GetRW())
   186  }
   187  
   188  func TestBasePeer_SendBlockHeaders(t *testing.T) {
   189  	header1 := blocks[0].Header()
   190  	header2 := blocks[1].Header()
   191  
   192  	sentHeaders := []*types.Header{header1, header2}
   193  
   194  	basePeer, _, oppositePipe := newBasePeer()
   195  	go func(t *testing.T) {
   196  		if err := basePeer.SendBlockHeaders(sentHeaders); err != nil {
   197  			t.Error(err)
   198  			return
   199  		}
   200  	}(t)
   201  	receivedMsg, err := oppositePipe.ReadMsg()
   202  	if err != nil {
   203  		t.Fatal(err)
   204  	}
   205  
   206  	var receivedHeaders []*types.Header
   207  	if err := receivedMsg.Decode(&receivedHeaders); err != nil {
   208  		t.Fatal(err)
   209  	}
   210  
   211  	assert.Equal(t, sentHeaders, receivedHeaders)
   212  }
   213  
   214  func TestBasePeer_SendFetchedBlockHeader(t *testing.T) {
   215  	sentHeader := blocks[0].Header()
   216  
   217  	basePeer, _, oppositePipe := newBasePeer()
   218  	go func(t *testing.T) {
   219  		if err := basePeer.SendFetchedBlockHeader(sentHeader); err != nil {
   220  			t.Error(err)
   221  			return
   222  		}
   223  	}(t)
   224  	receivedMsg, err := oppositePipe.ReadMsg()
   225  	if err != nil {
   226  		t.Fatal(err)
   227  	}
   228  
   229  	var receivedHeader types.Header
   230  	if err := receivedMsg.Decode(&receivedHeader); err != nil {
   231  		t.Fatal(err)
   232  	}
   233  
   234  	assert.Equal(t, sentHeader, &receivedHeader)
   235  }
   236  
   237  func TestBasePeer_SendNodeData(t *testing.T) {
   238  	sentData := [][]byte{hashes[0][:], hashes[1][:]}
   239  
   240  	basePeer, _, oppositePipe := newBasePeer()
   241  	go func(t *testing.T) {
   242  		if err := basePeer.SendNodeData(sentData); err != nil {
   243  			t.Error(err)
   244  			return
   245  		}
   246  	}(t)
   247  	receivedMsg, err := oppositePipe.ReadMsg()
   248  	if err != nil {
   249  		t.Fatal(err)
   250  	}
   251  
   252  	var receivedData [][]byte
   253  	if err := receivedMsg.Decode(&receivedData); err != nil {
   254  		t.Fatal(err)
   255  	}
   256  
   257  	assert.Equal(t, sentData, receivedData)
   258  }
   259  
   260  func TestBasePeer_FetchBlockHeader(t *testing.T) {
   261  	sentHash := hashes[0]
   262  
   263  	basePeer, _, oppositePipe := newBasePeer()
   264  	go func(t *testing.T) {
   265  		if err := basePeer.FetchBlockHeader(sentHash); err != nil {
   266  			t.Error(err)
   267  			return
   268  		}
   269  	}(t)
   270  	receivedMsg, err := oppositePipe.ReadMsg()
   271  	if err != nil {
   272  		t.Fatal(err)
   273  	}
   274  
   275  	var receivedHash common.Hash
   276  	if err := receivedMsg.Decode(&receivedHash); err != nil {
   277  		t.Fatal(err)
   278  	}
   279  
   280  	assert.Equal(t, sentHash, receivedHash)
   281  }
   282  
   283  func TestBasePeer_RequestBodies(t *testing.T) {
   284  	sentHashes := hashes
   285  	basePeer, _, oppositePipe := newBasePeer()
   286  	go func(t *testing.T) {
   287  		if err := basePeer.RequestBodies(sentHashes); err != nil {
   288  			t.Error(err)
   289  			return
   290  		}
   291  	}(t)
   292  	receivedMsg, err := oppositePipe.ReadMsg()
   293  	if err != nil {
   294  		t.Fatal(err)
   295  	}
   296  
   297  	var receivedHashes []common.Hash
   298  	if err := receivedMsg.Decode(&receivedHashes); err != nil {
   299  		t.Fatal(err)
   300  	}
   301  
   302  	assert.Equal(t, sentHashes, receivedHashes)
   303  }
   304  
   305  func TestBasePeer_FetchBlockBodies(t *testing.T) {
   306  	sentHashes := hashes
   307  	basePeer, _, oppositePipe := newBasePeer()
   308  	go func(t *testing.T) {
   309  		if err := basePeer.FetchBlockBodies(sentHashes); err != nil {
   310  			t.Error(err)
   311  			return
   312  		}
   313  	}(t)
   314  	receivedMsg, err := oppositePipe.ReadMsg()
   315  	if err != nil {
   316  		t.Fatal(err)
   317  	}
   318  
   319  	var receivedHashes []common.Hash
   320  	if err := receivedMsg.Decode(&receivedHashes); err != nil {
   321  		t.Fatal(err)
   322  	}
   323  
   324  	assert.Equal(t, sentHashes, receivedHashes)
   325  }
   326  
   327  func TestBasePeer_RequestNodeData(t *testing.T) {
   328  	sentHashes := hashes
   329  	basePeer, _, oppositePipe := newBasePeer()
   330  	go func(t *testing.T) {
   331  		if err := basePeer.RequestNodeData(sentHashes); err != nil {
   332  			t.Error(err)
   333  			return
   334  		}
   335  	}(t)
   336  	receivedMsg, err := oppositePipe.ReadMsg()
   337  	if err != nil {
   338  		t.Fatal(err)
   339  	}
   340  
   341  	var receivedHashes []common.Hash
   342  	if err := receivedMsg.Decode(&receivedHashes); err != nil {
   343  		t.Fatal(err)
   344  	}
   345  
   346  	assert.Equal(t, sentHashes, receivedHashes)
   347  }
   348  
   349  func TestBasePeer_RequestReceipts(t *testing.T) {
   350  	sentHashes := hashes
   351  	basePeer, _, oppositePipe := newBasePeer()
   352  	go func(t *testing.T) {
   353  		if err := basePeer.RequestReceipts(sentHashes); err != nil {
   354  			t.Error(err)
   355  			return
   356  		}
   357  	}(t)
   358  	receivedMsg, err := oppositePipe.ReadMsg()
   359  	if err != nil {
   360  		t.Fatal(err)
   361  	}
   362  
   363  	var receivedHashes []common.Hash
   364  	if err := receivedMsg.Decode(&receivedHashes); err != nil {
   365  		t.Fatal(err)
   366  	}
   367  
   368  	assert.Equal(t, sentHashes, receivedHashes)
   369  }
   370  
   371  func TestBasePeer_SendTransactionWithSortedByTime(t *testing.T) {
   372  	// Generate a batch of accounts to start with
   373  	keys := make([]*ecdsa.PrivateKey, 5)
   374  	for i := 0; i < len(keys); i++ {
   375  		keys[i], _ = crypto.GenerateKey()
   376  	}
   377  	signer := types.LatestSignerForChainID(big.NewInt(1))
   378  
   379  	// Generate a batch of transactions.
   380  	txs := types.Transactions{}
   381  	for _, key := range keys {
   382  		tx, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), 100, big.NewInt(1), nil), signer, key)
   383  
   384  		txs = append(txs, tx)
   385  	}
   386  
   387  	// Shuffle transactions.
   388  	rand.Seed(time.Now().Unix())
   389  	rand.Shuffle(len(txs), func(i, j int) {
   390  		txs[i], txs[j] = txs[j], txs[i]
   391  	})
   392  
   393  	sortedTxs := make(types.Transactions, len(txs))
   394  	copy(sortedTxs, txs)
   395  
   396  	// Sort transaction by time.
   397  	sort.Sort(types.TxByTime(sortedTxs))
   398  
   399  	basePeer, _, oppositePipe := newBasePeer()
   400  	for _, tx := range txs {
   401  		assert.False(t, basePeer.KnowsTx(tx.Hash()))
   402  	}
   403  
   404  	go func(t *testing.T) {
   405  		if err := basePeer.SendTransactions(txs); err != nil {
   406  			t.Error(t)
   407  			return
   408  		}
   409  	}(t)
   410  
   411  	receivedMsg, err := oppositePipe.ReadMsg()
   412  	if err != nil {
   413  		t.Fatal(err)
   414  	}
   415  
   416  	var receivedTxs types.Transactions
   417  	if err := receivedMsg.Decode(&receivedTxs); err != nil {
   418  		t.Fatal(err)
   419  	}
   420  
   421  	assert.Equal(t, len(txs), len(receivedTxs))
   422  
   423  	// It should be received transaction with sorted by times.
   424  	for i, tx := range receivedTxs {
   425  		assert.True(t, basePeer.KnowsTx(tx.Hash()))
   426  		assert.Equal(t, sortedTxs[i].Hash(), tx.Hash())
   427  		assert.False(t, sortedTxs[i].Time().Equal(tx.Time()))
   428  	}
   429  }
   430  
   431  func TestBasePeer_ReSendTransactionWithSortedByTime(t *testing.T) {
   432  	// Generate a batch of accounts to start with
   433  	keys := make([]*ecdsa.PrivateKey, 5)
   434  	for i := 0; i < len(keys); i++ {
   435  		keys[i], _ = crypto.GenerateKey()
   436  	}
   437  	signer := types.LatestSignerForChainID(big.NewInt(1))
   438  
   439  	// Generate a batch of transactions.
   440  	txs := types.Transactions{}
   441  	for _, key := range keys {
   442  		tx, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), 100, big.NewInt(1), nil), signer, key)
   443  
   444  		txs = append(txs, tx)
   445  	}
   446  
   447  	// Shuffle transactions.
   448  	rand.Seed(time.Now().Unix())
   449  	rand.Shuffle(len(txs), func(i, j int) {
   450  		txs[i], txs[j] = txs[j], txs[i]
   451  	})
   452  
   453  	sortedTxs := make(types.Transactions, len(txs))
   454  	copy(sortedTxs, txs)
   455  
   456  	// Sort transaction by time.
   457  	sort.Sort(types.TxByTime(sortedTxs))
   458  
   459  	basePeer, _, oppositePipe := newBasePeer()
   460  	go func(t *testing.T) {
   461  		if err := basePeer.ReSendTransactions(txs); err != nil {
   462  			t.Error(t)
   463  			return
   464  		}
   465  	}(t)
   466  
   467  	receivedMsg, err := oppositePipe.ReadMsg()
   468  	if err != nil {
   469  		t.Fatal(err)
   470  	}
   471  
   472  	var receivedTxs types.Transactions
   473  	if err := receivedMsg.Decode(&receivedTxs); err != nil {
   474  		t.Fatal(err)
   475  	}
   476  
   477  	assert.Equal(t, len(txs), len(receivedTxs))
   478  
   479  	// It should be received transaction with sorted by times.
   480  	for i, tx := range receivedTxs {
   481  		assert.Equal(t, sortedTxs[i].Hash(), tx.Hash())
   482  		assert.False(t, sortedTxs[i].Time().Equal(tx.Time()))
   483  	}
   484  }
   485  
   486  func TestMultiChannelPeer_SendTransactionWithSortedByTime(t *testing.T) {
   487  	// Generate a batch of accounts to start with
   488  	keys := make([]*ecdsa.PrivateKey, 5)
   489  	for i := 0; i < len(keys); i++ {
   490  		keys[i], _ = crypto.GenerateKey()
   491  	}
   492  	signer := types.LatestSignerForChainID(big.NewInt(1))
   493  
   494  	// Generate a batch of transactions.
   495  	txs := types.Transactions{}
   496  	for _, key := range keys {
   497  		tx, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), 100, big.NewInt(1), nil), signer, key)
   498  
   499  		txs = append(txs, tx)
   500  	}
   501  
   502  	// Shuffle transactions.
   503  	rand.Seed(time.Now().Unix())
   504  	rand.Shuffle(len(txs), func(i, j int) {
   505  		txs[i], txs[j] = txs[j], txs[i]
   506  	})
   507  
   508  	sortedTxs := make(types.Transactions, len(txs))
   509  	copy(sortedTxs, txs)
   510  
   511  	// Sort transaction by time.
   512  	sort.Sort(types.TxByTime(sortedTxs))
   513  
   514  	_, oppositePipe1, oppositePipe2 := newBasePeer()
   515  	multiPeer, _ := newPeerWithRWs(version, p2pPeers[0], []p2p.MsgReadWriter{oppositePipe1, oppositePipe2})
   516  
   517  	for _, tx := range txs {
   518  		assert.False(t, multiPeer.KnowsTx(tx.Hash()))
   519  	}
   520  
   521  	go func(t *testing.T) {
   522  		if err := multiPeer.SendTransactions(txs); err != nil {
   523  			t.Error(t)
   524  			return
   525  		}
   526  	}(t)
   527  
   528  	receivedMsg, err := oppositePipe1.ReadMsg()
   529  	if err != nil {
   530  		t.Fatal(err)
   531  	}
   532  
   533  	var receivedTxs types.Transactions
   534  	if err := receivedMsg.Decode(&receivedTxs); err != nil {
   535  		t.Fatal(err)
   536  	}
   537  
   538  	assert.Equal(t, len(txs), len(receivedTxs))
   539  
   540  	// It should be received transaction with sorted by times.
   541  	for i, tx := range receivedTxs {
   542  		assert.True(t, multiPeer.KnowsTx(tx.Hash()))
   543  		assert.Equal(t, sortedTxs[i].Hash(), tx.Hash())
   544  		assert.False(t, sortedTxs[i].Time().Equal(tx.Time()))
   545  	}
   546  }
   547  
   548  func TestMultiChannelPeer_ReSendTransactionWithSortedByTime(t *testing.T) {
   549  	// Generate a batch of accounts to start with
   550  	keys := make([]*ecdsa.PrivateKey, 5)
   551  	for i := 0; i < len(keys); i++ {
   552  		keys[i], _ = crypto.GenerateKey()
   553  	}
   554  	signer := types.LatestSignerForChainID(big.NewInt(1))
   555  
   556  	// Generate a batch of transactions.
   557  	txs := types.Transactions{}
   558  	for _, key := range keys {
   559  		tx, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), 100, big.NewInt(1), nil), signer, key)
   560  
   561  		txs = append(txs, tx)
   562  	}
   563  
   564  	// Shuffle transactions.
   565  	rand.Seed(time.Now().Unix())
   566  	rand.Shuffle(len(txs), func(i, j int) {
   567  		txs[i], txs[j] = txs[j], txs[i]
   568  	})
   569  
   570  	sortedTxs := make(types.Transactions, len(txs))
   571  	copy(sortedTxs, txs)
   572  
   573  	// Sort transaction by time.
   574  	sort.Sort(types.TxByTime(sortedTxs))
   575  
   576  	_, oppositePipe1, oppositePipe2 := newBasePeer()
   577  	multiPeer, _ := newPeerWithRWs(version, p2pPeers[0], []p2p.MsgReadWriter{oppositePipe1, oppositePipe2})
   578  
   579  	for _, tx := range txs {
   580  		assert.False(t, multiPeer.KnowsTx(tx.Hash()))
   581  	}
   582  
   583  	go func(t *testing.T) {
   584  		if err := multiPeer.ReSendTransactions(txs); err != nil {
   585  			t.Error(t)
   586  			return
   587  		}
   588  	}(t)
   589  
   590  	receivedMsg, err := oppositePipe1.ReadMsg()
   591  	if err != nil {
   592  		t.Fatal(err)
   593  	}
   594  
   595  	var receivedTxs types.Transactions
   596  	if err := receivedMsg.Decode(&receivedTxs); err != nil {
   597  		t.Fatal(err)
   598  	}
   599  
   600  	assert.Equal(t, len(txs), len(receivedTxs))
   601  
   602  	// It should be received transaction with sorted by times.
   603  	for i, tx := range receivedTxs {
   604  		assert.Equal(t, sortedTxs[i].Hash(), tx.Hash())
   605  		assert.False(t, sortedTxs[i].Time().Equal(tx.Time()))
   606  	}
   607  }