github.com/turingchain2020/turingchain@v1.1.21/system/mempool/mempool_test.go (about)

     1  // Copyright Turing Corp. 2018 All Rights Reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package mempool
     6  
     7  import (
     8  	"errors"
     9  	"math/rand"
    10  	"testing"
    11  
    12  	"github.com/turingchain2020/turingchain/util"
    13  
    14  	"github.com/golang/protobuf/proto"
    15  
    16  	"github.com/turingchain2020/turingchain/blockchain"
    17  	"github.com/turingchain2020/turingchain/common"
    18  	"github.com/turingchain2020/turingchain/common/address"
    19  	"github.com/turingchain2020/turingchain/common/crypto"
    20  	"github.com/turingchain2020/turingchain/common/limits"
    21  	"github.com/turingchain2020/turingchain/common/log"
    22  	"github.com/turingchain2020/turingchain/executor"
    23  	"github.com/turingchain2020/turingchain/queue"
    24  	"github.com/turingchain2020/turingchain/store"
    25  	_ "github.com/turingchain2020/turingchain/system/consensus/init"
    26  	_ "github.com/turingchain2020/turingchain/system/crypto/init"
    27  	cty "github.com/turingchain2020/turingchain/system/dapp/coins/types"
    28  	_ "github.com/turingchain2020/turingchain/system/dapp/init"
    29  	_ "github.com/turingchain2020/turingchain/system/store/init"
    30  	"github.com/turingchain2020/turingchain/types"
    31  	"github.com/stretchr/testify/require"
    32  )
    33  
    34  //----------------------------- data for testing ---------------------------------
    35  var (
    36  	c, _       = crypto.New(types.GetSignName("", types.SECP256K1))
    37  	hex        = "CC38546E9E659D15E6B4893F0AB32A06D103931A8230B0BDE71459D2B27D6944"
    38  	a, _       = common.FromHex(hex)
    39  	privKey, _ = c.PrivKeyFromBytes(a)
    40  	random     *rand.Rand
    41  	mainPriv   crypto.PrivKey
    42  	toAddr     = address.PubKeyToAddress(privKey.PubKey().Bytes()).String()
    43  	amount     = int64(1e8)
    44  	v          = &cty.CoinsAction_Transfer{Transfer: &types.AssetsTransfer{Amount: amount}}
    45  	bigByte    = make([]byte, 99510)
    46  	transfer   = &cty.CoinsAction{Value: v, Ty: cty.CoinsActionTransfer}
    47  	tx1        = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 1000000, Expire: 4, To: toAddr}
    48  	tx2        = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 100000000, Expire: 0, To: toAddr}
    49  	tx3        = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 200000000, Expire: 0, To: toAddr}
    50  	tx4        = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 300000000, Expire: 0, To: toAddr}
    51  	tx5        = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 400000000, Expire: 0, To: toAddr}
    52  	tx6        = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 500000000, Expire: 0, To: toAddr}
    53  	tx7        = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 600000000, Expire: 0, To: toAddr}
    54  	tx8        = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 700000000, Expire: 0, To: toAddr}
    55  	tx9        = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 800000000, Expire: 0, To: toAddr}
    56  	tx10       = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 900000000, Expire: 0, To: toAddr}
    57  	tx11       = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 450000000, Expire: 0, To: toAddr}
    58  	tx12       = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 460000000, Expire: 0, To: toAddr}
    59  	tx13       = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 100, Expire: 0, To: toAddr}
    60  	tx14       = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 100000000, Expire: 0, To: "notaddress"}
    61  	tx15       = &types.Transaction{Execer: []byte("user.write"), Payload: types.Encode(transfer), Fee: 100000000, Expire: 0, To: toAddr}
    62  	tx16       = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 100000, Expire: 3, To: toAddr}
    63  	tx17       = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 100000, Expire: 4, To: toAddr}
    64  	tx18       = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 4000000, Expire: 4, To: toAddr}
    65  
    66  	bigTx1  = &types.Transaction{Execer: []byte("user.write"), Payload: bigByte, Fee: 100100000, Expire: 0, To: toAddr}
    67  	bigTx2  = &types.Transaction{Execer: []byte("user.write"), Payload: bigByte, Fee: 100100000, Expire: 11, To: toAddr}
    68  	bigTx3  = &types.Transaction{Execer: []byte("user.write"), Payload: bigByte, Fee: 1001000000, Expire: 11, To: toAddr}
    69  	bigTx4  = &types.Transaction{Execer: []byte("user.write"), Payload: bigByte, Fee: 1001000000, Expire: 12, To: toAddr}
    70  	bigTx5  = &types.Transaction{Execer: []byte("user.write"), Payload: bigByte, Fee: 1001000000, Expire: 13, To: toAddr}
    71  	bigTx6  = &types.Transaction{Execer: []byte("user.write"), Payload: bigByte, Fee: 1001000000, Expire: 14, To: toAddr}
    72  	bigTx7  = &types.Transaction{Execer: []byte("user.write"), Payload: bigByte, Fee: 1001000000, Expire: 15, To: toAddr}
    73  	bigTx8  = &types.Transaction{Execer: []byte("user.write"), Payload: bigByte, Fee: 1001000000, Expire: 16, To: toAddr}
    74  	bigTx9  = &types.Transaction{Execer: []byte("user.write"), Payload: bigByte, Fee: 1001000000, Expire: 17, To: toAddr}
    75  	bigTx10 = &types.Transaction{Execer: []byte("user.write"), Payload: bigByte, Fee: 1001000000, Expire: 18, To: toAddr}
    76  	bigTx11 = &types.Transaction{Execer: []byte("user.write"), Payload: bigByte, Fee: 1001000000, Expire: 19, To: toAddr}
    77  )
    78  
    79  //var privTo, _ = c.GenKey()
    80  //var ad = address.PubKeyToAddress(privKey.PubKey().Bytes()).String()
    81  
    82  var blk = &types.Block{
    83  	Version:    1,
    84  	ParentHash: []byte("parent hash"),
    85  	TxHash:     []byte("tx hash"),
    86  	Height:     2,
    87  	BlockTime:  1,
    88  	Txs:        []*types.Transaction{tx3, tx5},
    89  }
    90  
    91  func init() {
    92  	err := limits.SetLimits()
    93  	if err != nil {
    94  		panic(err)
    95  	}
    96  	random = rand.New(rand.NewSource(types.Now().UnixNano()))
    97  	queue.DisableLog()
    98  	log.SetLogLevel("err") // 输出WARN(含)以下log
    99  	mainPriv = getprivkey("CC38546E9E659D15E6B4893F0AB32A06D103931A8230B0BDE71459D2B27D6944")
   100  	tx1.Sign(types.SECP256K1, privKey)
   101  	tx2.Sign(types.SECP256K1, privKey)
   102  	tx3.Sign(types.SECP256K1, privKey)
   103  	tx4.Sign(types.SECP256K1, privKey)
   104  	tx5.Sign(types.SECP256K1, privKey)
   105  	tx6.Sign(types.SECP256K1, privKey)
   106  	tx7.Sign(types.SECP256K1, privKey)
   107  	tx8.Sign(types.SECP256K1, privKey)
   108  	tx9.Sign(types.SECP256K1, privKey)
   109  	tx10.Sign(types.SECP256K1, privKey)
   110  	tx11.Sign(types.SECP256K1, privKey)
   111  	tx12.Sign(types.SECP256K1, privKey)
   112  	tx13.Sign(types.SECP256K1, privKey)
   113  	tx14.Sign(types.SECP256K1, privKey)
   114  	tx15.Sign(types.SECP256K1, privKey)
   115  	tx16.Sign(types.SECP256K1, privKey)
   116  	tx17.Sign(types.SECP256K1, privKey)
   117  	tx18.Sign(types.SECP256K1, privKey)
   118  	bigTx1.Sign(types.SECP256K1, privKey)
   119  	bigTx2.Sign(types.SECP256K1, privKey)
   120  	bigTx3.Sign(types.SECP256K1, privKey)
   121  	bigTx4.Sign(types.SECP256K1, privKey)
   122  	bigTx5.Sign(types.SECP256K1, privKey)
   123  	bigTx6.Sign(types.SECP256K1, privKey)
   124  	bigTx7.Sign(types.SECP256K1, privKey)
   125  	bigTx8.Sign(types.SECP256K1, privKey)
   126  	bigTx9.Sign(types.SECP256K1, privKey)
   127  	bigTx10.Sign(types.SECP256K1, privKey)
   128  	bigTx11.Sign(types.SECP256K1, privKey)
   129  
   130  }
   131  
   132  func getprivkey(key string) crypto.PrivKey {
   133  	cr, err := crypto.New(types.GetSignName("", types.SECP256K1))
   134  	if err != nil {
   135  		panic(err)
   136  	}
   137  	bkey, err := common.FromHex(key)
   138  	if err != nil {
   139  		panic(err)
   140  	}
   141  	priv, err := cr.PrivKeyFromBytes(bkey)
   142  	if err != nil {
   143  		panic(err)
   144  	}
   145  	return priv
   146  }
   147  
   148  func initEnv3() (queue.Queue, queue.Module, queue.Module, *Mempool) {
   149  	cfg := types.NewTuringchainConfig(types.ReadFile("../../cmd/turingchain/turingchain.test.toml"))
   150  	mcfg := cfg.GetModuleConfig()
   151  	var q = queue.New("channel")
   152  	q.SetConfig(cfg)
   153  	mcfg.Consensus.Minerstart = false
   154  	chain := blockchain.New(cfg)
   155  	chain.SetQueueClient(q.Client())
   156  
   157  	exec := executor.New(cfg)
   158  	exec.SetQueueClient(q.Client())
   159  
   160  	cfg.SetMinFee(0)
   161  	s := store.New(cfg)
   162  	s.SetQueueClient(q.Client())
   163  	subConfig := SubConfig{mcfg.Mempool.PoolCacheSize, mcfg.Mempool.MinTxFeeRate}
   164  	mem := NewMempool(mcfg.Mempool)
   165  	mem.SetQueueCache(NewSimpleQueue(subConfig))
   166  	mem.SetQueueClient(q.Client())
   167  	mem.Wait()
   168  	return q, chain, s, mem
   169  }
   170  
   171  func initEnv(size int) (queue.Queue, *Mempool) {
   172  	if size == 0 {
   173  		size = 100
   174  	}
   175  	cfg := types.NewTuringchainConfig(types.ReadFile("../../cmd/turingchain/turingchain.test.toml"))
   176  	mcfg := cfg.GetModuleConfig()
   177  	var q = queue.New("channel")
   178  	q.SetConfig(cfg)
   179  	blockchainProcess(q)
   180  	execProcess(q)
   181  	mcfg.Mempool.PoolCacheSize = int64(size)
   182  	subConfig := SubConfig{mcfg.Mempool.PoolCacheSize, mcfg.Mempool.MinTxFeeRate}
   183  	mem := NewMempool(mcfg.Mempool)
   184  	mem.SetQueueCache(NewSimpleQueue(subConfig))
   185  	mem.SetQueueClient(q.Client())
   186  	mem.setSync(true)
   187  	mem.SetMinFee(cfg.GetMinTxFeeRate())
   188  	mem.Wait()
   189  	return q, mem
   190  }
   191  
   192  func initEnv4(size int) (queue.Queue, *Mempool) {
   193  	if size == 0 {
   194  		size = 100
   195  	}
   196  	cfg := types.NewTuringchainConfig(types.ReadFile("testdata/turingchain.test.toml"))
   197  	mcfg := cfg.GetModuleConfig()
   198  	var q = queue.New("channel")
   199  	q.SetConfig(cfg)
   200  	blockchainProcess(q)
   201  	execProcess(q)
   202  	mcfg.Mempool.PoolCacheSize = int64(size)
   203  	subConfig := SubConfig{mcfg.Mempool.PoolCacheSize, mcfg.Mempool.MinTxFeeRate}
   204  	mem := NewMempool(mcfg.Mempool)
   205  	mem.SetQueueCache(NewSimpleQueue(subConfig))
   206  	mem.SetQueueClient(q.Client())
   207  	mem.setSync(true)
   208  	mem.SetMinFee(cfg.GetMinTxFeeRate())
   209  	mem.Wait()
   210  	return q, mem
   211  }
   212  
   213  func createTx(cfg *types.TuringchainConfig, priv crypto.PrivKey, to string, amount int64) *types.Transaction {
   214  	v := &cty.CoinsAction_Transfer{Transfer: &types.AssetsTransfer{Amount: amount}}
   215  	transfer := &cty.CoinsAction{Value: v, Ty: cty.CoinsActionTransfer}
   216  	tx := &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 1e6, To: to}
   217  	tx.Nonce = rand.Int63()
   218  	tx.ChainID = cfg.GetChainID()
   219  	tx.Sign(types.SECP256K1, priv)
   220  	return tx
   221  }
   222  
   223  func genaddress() (string, crypto.PrivKey) {
   224  	cr, err := crypto.New(types.GetSignName("", types.SECP256K1))
   225  	if err != nil {
   226  		panic(err)
   227  	}
   228  	privto, err := cr.GenKey()
   229  	if err != nil {
   230  		panic(err)
   231  	}
   232  	addrto := address.PubKeyToAddress(privto.PubKey().Bytes())
   233  	return addrto.String(), privto
   234  }
   235  
   236  func TestAddEmptyTx(t *testing.T) {
   237  	q, mem := initEnv(0)
   238  	defer q.Close()
   239  	defer mem.Close()
   240  
   241  	msg := mem.client.NewMessage("mempool", types.EventTx, nil)
   242  	mem.client.Send(msg, true)
   243  	resp, err := mem.client.Wait(msg)
   244  	if err != nil {
   245  		t.Error(err)
   246  		return
   247  	}
   248  
   249  	if string(resp.GetData().(*types.Reply).GetMsg()) != types.ErrEmptyTx.Error() {
   250  		t.Error("TestAddEmptyTx failed")
   251  	}
   252  }
   253  
   254  func TestAddTx(t *testing.T) {
   255  	q, mem := initEnv(1)
   256  	defer q.Close()
   257  	defer mem.Close()
   258  	msg := mem.client.NewMessage("mempool", types.EventTx, tx2)
   259  	mem.client.Send(msg, true)
   260  	mem.client.Wait(msg)
   261  	if mem.Size() != 1 {
   262  		t.Error("TestAddTx failed")
   263  	}
   264  }
   265  
   266  func TestAddDuplicatedTx(t *testing.T) {
   267  	q, mem := initEnv(100)
   268  	defer q.Close()
   269  	defer mem.Close()
   270  
   271  	msg1 := mem.client.NewMessage("mempool", types.EventTx, tx2)
   272  	err := mem.client.Send(msg1, true)
   273  	if err != nil {
   274  		t.Error(err)
   275  		return
   276  	}
   277  	msg1, err = mem.client.Wait(msg1)
   278  	if err != nil {
   279  		t.Error(err)
   280  		return
   281  	}
   282  	reply := msg1.GetData().(*types.Reply)
   283  	err = checkReply(reply)
   284  	if err != nil {
   285  		t.Error(err)
   286  		return
   287  	}
   288  	if mem.Size() != 1 {
   289  		t.Error("TestAddDuplicatedTx failed", "size", mem.Size())
   290  	}
   291  	msg2 := mem.client.NewMessage("mempool", types.EventTx, tx2)
   292  	mem.client.Send(msg2, true)
   293  	mem.client.Wait(msg2)
   294  
   295  	if mem.Size() != 1 {
   296  		t.Error("TestAddDuplicatedTx failed", "size", mem.Size())
   297  	}
   298  }
   299  
   300  func checkReply(reply *types.Reply) error {
   301  	if !reply.GetIsOk() {
   302  		return errors.New(string(reply.GetMsg()))
   303  	}
   304  	return nil
   305  }
   306  
   307  func add4Tx(client queue.Client) error {
   308  	msg1 := client.NewMessage("mempool", types.EventTx, tx1)
   309  	msg2 := client.NewMessage("mempool", types.EventTx, tx2)
   310  	msg3 := client.NewMessage("mempool", types.EventTx, tx3)
   311  	msg4 := client.NewMessage("mempool", types.EventTx, tx4)
   312  	client.Send(msg1, true)
   313  	_, err := client.Wait(msg1)
   314  	if err != nil {
   315  		return err
   316  	}
   317  
   318  	client.Send(msg2, true)
   319  	_, err = client.Wait(msg2)
   320  	if err != nil {
   321  		return err
   322  	}
   323  
   324  	client.Send(msg3, true)
   325  	_, err = client.Wait(msg3)
   326  	if err != nil {
   327  		return err
   328  	}
   329  
   330  	client.Send(msg4, true)
   331  	_, err = client.Wait(msg4)
   332  	return err
   333  }
   334  
   335  func add4TxHash(client queue.Client) ([]string, error) {
   336  	msg1 := client.NewMessage("mempool", types.EventTx, tx5)
   337  	msg2 := client.NewMessage("mempool", types.EventTx, tx2)
   338  	msg3 := client.NewMessage("mempool", types.EventTx, tx3)
   339  	msg4 := client.NewMessage("mempool", types.EventTx, tx4)
   340  	hashList := []string{string(tx5.Hash()), string(tx2.Hash()), string(tx3.Hash()), string(tx4.Hash())}
   341  	client.Send(msg1, true)
   342  	_, err := client.Wait(msg1)
   343  	if err != nil {
   344  		return nil, err
   345  	}
   346  
   347  	client.Send(msg2, true)
   348  	_, err = client.Wait(msg2)
   349  	if err != nil {
   350  		return nil, err
   351  	}
   352  
   353  	client.Send(msg3, true)
   354  	_, err = client.Wait(msg3)
   355  	if err != nil {
   356  		return nil, err
   357  	}
   358  
   359  	client.Send(msg4, true)
   360  	_, err = client.Wait(msg4)
   361  	if err != nil {
   362  		return nil, err
   363  	}
   364  	return hashList, nil
   365  }
   366  
   367  func add10Tx(client queue.Client) error {
   368  	err := add4Tx(client)
   369  	if err != nil {
   370  		return err
   371  	}
   372  	txs := []*types.Transaction{tx5, tx6, tx7, tx8, tx9, tx10}
   373  	for _, tx := range txs {
   374  		msg := client.NewMessage("mempool", types.EventTx, tx)
   375  		client.Send(msg, true)
   376  		_, err = client.Wait(msg)
   377  		if err != nil {
   378  			return err
   379  		}
   380  	}
   381  	return nil
   382  }
   383  
   384  func TestEventTxList(t *testing.T) {
   385  	q, mem := initEnv(0)
   386  	defer q.Close()
   387  	defer mem.Close()
   388  
   389  	// add tx
   390  	hashes, err := add4TxHash(mem.client)
   391  	if err != nil {
   392  		t.Error("add tx error", err.Error())
   393  		return
   394  	}
   395  
   396  	msg1 := mem.client.NewMessage("mempool", types.EventTxList, &types.TxHashList{Count: 2, Hashes: nil})
   397  	mem.client.Send(msg1, true)
   398  	data1, err := mem.client.Wait(msg1)
   399  	if err != nil {
   400  		t.Error(err)
   401  		return
   402  	}
   403  	txs1 := data1.GetData().(*types.ReplyTxList).GetTxs()
   404  
   405  	if len(txs1) != 2 {
   406  		t.Error("get txlist number error")
   407  	}
   408  
   409  	var hashList [][]byte
   410  	for i, tx := range txs1 {
   411  		hashList = append(hashList, tx.Hash())
   412  		if hashes[i] != string(tx.Hash()) {
   413  			t.Error("gettxlist not in time order1")
   414  		}
   415  	}
   416  	msg2 := mem.client.NewMessage("mempool", types.EventTxList, &types.TxHashList{Count: 1, Hashes: hashList})
   417  	mem.client.Send(msg2, true)
   418  	data2, err := mem.client.Wait(msg2)
   419  	if err != nil {
   420  		t.Error(err)
   421  		return
   422  	}
   423  	txs2 := data2.GetData().(*types.ReplyTxList).GetTxs()
   424  	for i, tx := range txs2 {
   425  		hashList = append(hashList, tx.Hash())
   426  		if hashes[2+i] != string(tx.Hash()) {
   427  			t.Error("gettxlist not in time order2")
   428  		}
   429  	}
   430  OutsideLoop:
   431  	for _, t1 := range txs1 {
   432  		for _, t2 := range txs2 {
   433  			if string(t1.Hash()) == string(t2.Hash()) {
   434  				t.Error("TestGetTxList failed")
   435  				break OutsideLoop
   436  			}
   437  		}
   438  	}
   439  }
   440  
   441  func TestEventDelTxList(t *testing.T) {
   442  	q, mem := initEnv(0)
   443  	defer q.Close()
   444  	defer mem.Close()
   445  
   446  	// add tx
   447  	hashes, err := add4TxHash(mem.client)
   448  	if err != nil {
   449  		t.Error("add tx error", err.Error())
   450  		return
   451  	}
   452  
   453  	hashBytes := [][]byte{[]byte(hashes[0]), []byte(hashes[1])}
   454  	msg := mem.client.NewMessage("mempool", types.EventDelTxList, &types.TxHashList{Count: 2, Hashes: hashBytes})
   455  	mem.client.Send(msg, true)
   456  	_, err = mem.client.Wait(msg)
   457  	if err != nil {
   458  		t.Error(err)
   459  		return
   460  	}
   461  
   462  	if mem.Size() != 2 {
   463  		t.Error("TestEventDelTxList failed")
   464  	}
   465  }
   466  
   467  func TestAddMoreTxThanPoolSize(t *testing.T) {
   468  	q, mem := initEnv(4)
   469  	defer q.Close()
   470  	defer mem.Close()
   471  
   472  	err := add4Tx(mem.client)
   473  	require.Nil(t, err)
   474  
   475  	msg5 := mem.client.NewMessage("mempool", types.EventTx, tx5)
   476  	mem.client.Send(msg5, true)
   477  	mem.client.Wait(msg5)
   478  
   479  	if mem.Size() != 4 || mem.cache.Exist(string(tx5.Hash())) {
   480  		t.Error("TestAddMoreTxThanPoolSize failed", mem.Size(), mem.cache.Exist(string(tx5.Hash())))
   481  	}
   482  }
   483  
   484  func TestAddMoreTxThanMaxAccountTx(t *testing.T) {
   485  	q, mem := initEnv(4)
   486  	mem.cfg.MaxTxNumPerAccount = 2
   487  	defer q.Close()
   488  	defer mem.Close()
   489  
   490  	err := add4Tx(mem.client)
   491  	if err != nil {
   492  		t.Error("add tx error", err.Error())
   493  		return
   494  	}
   495  	if mem.Size() != 2 {
   496  		t.Error("TestAddMoreTxThanMaxAccountTx failed", "size", mem.Size())
   497  	}
   498  }
   499  
   500  func TestRemoveTxOfBlock(t *testing.T) {
   501  	q, mem := initEnv(0)
   502  	defer q.Close()
   503  	defer mem.Close()
   504  
   505  	err := add4Tx(mem.client)
   506  	if err != nil {
   507  		t.Error("add tx error", err.Error())
   508  		return
   509  	}
   510  
   511  	blkDetail := &types.BlockDetail{Block: blk}
   512  	msg5 := mem.client.NewMessage("mempool", types.EventAddBlock, blkDetail)
   513  	mem.client.Send(msg5, false)
   514  
   515  	msg := mem.client.NewMessage("mempool", types.EventGetMempoolSize, nil)
   516  	mem.client.Send(msg, true)
   517  
   518  	reply, err := mem.client.Wait(msg)
   519  
   520  	if err != nil {
   521  		t.Error(err)
   522  		return
   523  	}
   524  	require.Equal(t, int64(3), reply.GetData().(*types.MempoolSize).Size)
   525  }
   526  
   527  func TestAddBlockedTx(t *testing.T) {
   528  	q, mem := initEnv(0)
   529  	defer q.Close()
   530  	defer mem.Close()
   531  
   532  	msg1 := mem.client.NewMessage("mempool", types.EventTx, tx3)
   533  	err := mem.client.Send(msg1, true)
   534  	require.Nil(t, err)
   535  	_, err = mem.client.Wait(msg1)
   536  	require.Nil(t, err)
   537  	blkDetail := &types.BlockDetail{Block: blk}
   538  	msg2 := mem.client.NewMessage("mempool", types.EventAddBlock, blkDetail)
   539  	mem.client.Send(msg2, false)
   540  
   541  	msg3 := mem.client.NewMessage("mempool", types.EventTx, tx3)
   542  	err = mem.client.Send(msg3, true)
   543  	require.Nil(t, err)
   544  	resp, err := mem.client.Wait(msg3)
   545  	require.Nil(t, err)
   546  	if string(resp.GetData().(*types.Reply).GetMsg()) != types.ErrDupTx.Error() {
   547  		t.Error("TestAddBlockedTx failed")
   548  	}
   549  }
   550  
   551  func TestDuplicateMempool(t *testing.T) {
   552  	q, mem := initEnv(0)
   553  	defer q.Close()
   554  	defer mem.Close()
   555  
   556  	// add 10 txs
   557  	err := add10Tx(mem.client)
   558  	if err != nil {
   559  		t.Error("add tx error", err.Error())
   560  		return
   561  	}
   562  	require.Equal(t, mem.Size(), 10)
   563  	msg := mem.client.NewMessage("mempool", types.EventGetMempool, nil)
   564  	mem.client.Send(msg, true)
   565  
   566  	reply, err := mem.client.Wait(msg)
   567  
   568  	if err != nil {
   569  		t.Error(err)
   570  		return
   571  	}
   572  
   573  	if len(reply.GetData().(*types.ReplyTxList).GetTxs()) != 10 || mem.Size() != 10 {
   574  		t.Error("TestDuplicateMempool failed")
   575  	}
   576  }
   577  
   578  func TestGetLatestTx(t *testing.T) {
   579  	q, mem := initEnv(0)
   580  	defer q.Close()
   581  	defer mem.Close()
   582  
   583  	// add 10 txs
   584  	err := add10Tx(mem.client)
   585  	if err != nil {
   586  		t.Error("add tx error", err.Error())
   587  		return
   588  	}
   589  
   590  	msg11 := mem.client.NewMessage("mempool", types.EventTx, tx11)
   591  	mem.client.Send(msg11, true)
   592  	mem.client.Wait(msg11)
   593  
   594  	msg := mem.client.NewMessage("mempool", types.EventGetLastMempool, nil)
   595  	mem.client.Send(msg, true)
   596  
   597  	reply, err := mem.client.Wait(msg)
   598  
   599  	if err != nil {
   600  		t.Error(err)
   601  		return
   602  	}
   603  
   604  	if len(reply.GetData().(*types.ReplyTxList).GetTxs()) != 10 || mem.Size() != 11 {
   605  		t.Error("TestGetLatestTx failed", len(reply.GetData().(*types.ReplyTxList).GetTxs()), mem.Size())
   606  	}
   607  }
   608  
   609  func testProperFee(t *testing.T, client queue.Client, req *types.ReqProperFee, expectFee int64) int64 {
   610  	msg := client.NewMessage("mempool", types.EventGetProperFee, req)
   611  	client.Send(msg, true)
   612  	reply, err := client.Wait(msg)
   613  	if err != nil {
   614  		t.Error(err)
   615  		return 0
   616  	}
   617  	fee := reply.GetData().(*types.ReplyProperFee).GetProperFee()
   618  	require.Equal(t, expectFee, fee)
   619  	return fee
   620  }
   621  
   622  func TestGetProperFee(t *testing.T) {
   623  	q, mem := initEnv(0)
   624  	cfg := q.GetConfig()
   625  	defer q.Close()
   626  	defer mem.Close()
   627  	defer func() {
   628  		mem.cfg.IsLevelFee = false
   629  	}()
   630  
   631  	// add 10 txs
   632  	err := add10Tx(mem.client)
   633  	if err != nil {
   634  		t.Error("add tx error", err.Error())
   635  		return
   636  	}
   637  	maxTxNum := cfg.GetP(mem.Height()).MaxTxNumber
   638  	maxSize := types.MaxBlockSize
   639  	msg11 := mem.client.NewMessage("mempool", types.EventTx, tx11)
   640  	mem.client.Send(msg11, true)
   641  	mem.client.Wait(msg11)
   642  
   643  	baseFee := testProperFee(t, mem.client, nil, mem.cfg.MinTxFeeRate)
   644  	mem.cfg.IsLevelFee = true
   645  	testProperFee(t, mem.client, nil, baseFee)
   646  	testProperFee(t, mem.client, &types.ReqProperFee{}, baseFee)
   647  	//more than 1/2 max num
   648  	testProperFee(t, mem.client, &types.ReqProperFee{TxCount: int32(maxTxNum / 2)}, 100*baseFee)
   649  	//more than 1/10 max num
   650  	testProperFee(t, mem.client, &types.ReqProperFee{TxCount: int32(maxTxNum / 10)}, 10*baseFee)
   651  	//more than 1/20 max size
   652  	testProperFee(t, mem.client, &types.ReqProperFee{TxCount: 1, TxSize: int32(maxSize / 20)}, 100*baseFee)
   653  	//more than 1/100 max size
   654  	testProperFee(t, mem.client, &types.ReqProperFee{TxCount: 1, TxSize: int32(maxSize / 100)}, 10*baseFee)
   655  }
   656  
   657  func TestCheckLowFee(t *testing.T) {
   658  	q, mem := initEnv(0)
   659  	defer q.Close()
   660  	defer mem.Close()
   661  
   662  	mem.SetMinFee(1000)
   663  	msg := mem.client.NewMessage("mempool", types.EventTx, tx13)
   664  	mem.client.Send(msg, true)
   665  	resp, _ := mem.client.Wait(msg)
   666  
   667  	if string(resp.GetData().(*types.Reply).GetMsg()) != types.ErrTxFeeTooLow.Error() {
   668  		t.Error("TestCheckLowFee failed")
   669  	}
   670  }
   671  
   672  func TestCheckSignature(t *testing.T) {
   673  	q, mem := initEnv(0)
   674  	defer q.Close()
   675  	defer mem.Close()
   676  
   677  	// make wrong signature
   678  	tx12.Signature.Signature = tx12.Signature.Signature[5:]
   679  
   680  	msg := mem.client.NewMessage("mempool", types.EventTx, tx12)
   681  	mem.client.Send(msg, true)
   682  	resp, _ := mem.client.Wait(msg)
   683  
   684  	if string(resp.GetData().(*types.Reply).GetMsg()) != types.ErrSign.Error() {
   685  		t.Error("TestCheckSignature failed", string(resp.GetData().(*types.Reply).GetMsg()))
   686  	}
   687  }
   688  
   689  func TestCheckExpire1(t *testing.T) {
   690  	q, mem := initEnv(0)
   691  	defer q.Close()
   692  	defer mem.Close()
   693  	mem.setHeader(&types.Header{Height: 50, BlockTime: 1e9 + 1})
   694  	ctx1 := *tx1
   695  	msg := mem.client.NewMessage("mempool", types.EventTx, &ctx1)
   696  	mem.client.Send(msg, true)
   697  	resp, _ := mem.client.Wait(msg)
   698  	if string(resp.GetData().(*types.Reply).GetMsg()) != types.ErrTxExpire.Error() {
   699  		t.Error("TestCheckExpire failed", string(resp.GetData().(*types.Reply).GetMsg()))
   700  	}
   701  }
   702  
   703  func TestCheckExpire2(t *testing.T) {
   704  	q, mem := initEnv(0)
   705  	defer q.Close()
   706  	defer mem.Close()
   707  
   708  	// add tx
   709  	err := add4Tx(mem.client)
   710  	if err != nil {
   711  		t.Error("add tx error", err.Error())
   712  		return
   713  	}
   714  	mem.setHeader(&types.Header{Height: 50, BlockTime: 1e9 + 1})
   715  	msg := mem.client.NewMessage("mempool", types.EventTxList, &types.TxHashList{Count: 100})
   716  	mem.client.Send(msg, true)
   717  	data, err := mem.client.Wait(msg)
   718  
   719  	if err != nil {
   720  		t.Error(err)
   721  		return
   722  	}
   723  
   724  	txs := data.GetData().(*types.ReplyTxList).GetTxs()
   725  
   726  	if len(txs) != 3 {
   727  		t.Error("TestCheckExpire failed", len(txs))
   728  	}
   729  }
   730  
   731  func TestCheckExpire3(t *testing.T) {
   732  	q, mem := initEnv(0)
   733  	defer q.Close()
   734  	defer mem.Close()
   735  
   736  	// add tx
   737  	err := add4Tx(mem.client)
   738  	if err != nil {
   739  		t.Error("add tx error", err.Error())
   740  		return
   741  	}
   742  	mem.setHeader(&types.Header{Height: 50, BlockTime: 1e9 + 1})
   743  	require.Equal(t, mem.Size(), 4)
   744  	mem.removeExpired()
   745  	require.Equal(t, mem.Size(), 3)
   746  }
   747  
   748  func TestWrongToAddr(t *testing.T) {
   749  	q, mem := initEnv(0)
   750  	defer q.Close()
   751  	defer mem.Close()
   752  
   753  	msg := mem.client.NewMessage("mempool", types.EventTx, tx14)
   754  	mem.client.Send(msg, true)
   755  	resp, _ := mem.client.Wait(msg)
   756  
   757  	if string(resp.GetData().(*types.Reply).GetMsg()) != types.ErrInvalidAddress.Error() {
   758  		t.Error("TestWrongToAddr failed")
   759  	}
   760  }
   761  
   762  func TestExecToAddrNotMatch(t *testing.T) {
   763  	q, chain, s, mem := initEnv3()
   764  	defer q.Close()
   765  	defer mem.Close()
   766  	defer chain.Close()
   767  	defer s.Close()
   768  
   769  	msg := mem.client.NewMessage("mempool", types.EventTx, tx15)
   770  	mem.client.Send(msg, true)
   771  	resp, _ := mem.client.Wait(msg)
   772  	if string(resp.GetData().(*types.Reply).GetMsg()) != types.ErrToAddrNotSameToExecAddr.Error() {
   773  		t.Error("TestExecToAddrNotMatch failed", string(resp.GetData().(*types.Reply).GetMsg()))
   774  	}
   775  }
   776  
   777  func TestGetAddrTxs(t *testing.T) {
   778  	q, mem := initEnv(0)
   779  	defer q.Close()
   780  	defer mem.Close()
   781  
   782  	// add tx
   783  	_, err := add4TxHash(mem.client)
   784  	if err != nil {
   785  		t.Error("add tx error", err.Error())
   786  		return
   787  	}
   788  
   789  	ad := address.PubKeyToAddress(privKey.PubKey().Bytes()).String()
   790  	addrs := []string{ad}
   791  	msg := mem.client.NewMessage("mempool", types.EventGetAddrTxs, &types.ReqAddrs{Addrs: addrs})
   792  	mem.client.Send(msg, true)
   793  	data, err := mem.client.Wait(msg)
   794  	if err != nil {
   795  		t.Error(err)
   796  		return
   797  	}
   798  	txsFact := data.GetData().(*types.TransactionDetails).Txs
   799  	txsExpect := mem.GetAccTxs(&types.ReqAddrs{Addrs: addrs}).Txs
   800  	if len(txsExpect) != len(txsFact) {
   801  		t.Error("TestGetAddrTxs failed", "length not match")
   802  	}
   803  	same := 0
   804  	for _, i := range txsExpect {
   805  		for _, j := range txsFact {
   806  			if j.Tx == i.Tx {
   807  				same++
   808  				break
   809  			}
   810  		}
   811  	}
   812  	if same != len(txsExpect) {
   813  		t.Error("TestGetAddrTxs failed", same)
   814  	}
   815  }
   816  
   817  func TestDelBlock(t *testing.T) {
   818  	q, mem := initEnv(0)
   819  	defer q.Close()
   820  	defer mem.Close()
   821  	delBlock := blk
   822  	var blockDetail = &types.BlockDetail{Block: delBlock}
   823  
   824  	mem.setHeader(&types.Header{Height: 2, BlockTime: 1e9 + 1})
   825  	msg1 := mem.client.NewMessage("mempool", types.EventDelBlock, blockDetail)
   826  	mem.client.Send(msg1, true)
   827  
   828  	msg2 := mem.client.NewMessage("mempool", types.EventGetMempoolSize, nil)
   829  	mem.client.Send(msg2, true)
   830  
   831  	reply, err := mem.client.Wait(msg2)
   832  
   833  	if err != nil {
   834  		t.Error(err)
   835  		return
   836  	}
   837  	size := reply.GetData().(*types.MempoolSize).Size
   838  	if size != 2 {
   839  		t.Error("TestDelBlock failed")
   840  	}
   841  }
   842  
   843  func TestAddTxGroup(t *testing.T) {
   844  	q, mem := initEnv(0)
   845  	cfg := q.GetConfig()
   846  	defer q.Close()
   847  	defer mem.Close()
   848  	toAddr := "1PjMi9yGTjA9bbqUZa1Sj7dAUKyLA8KqE1"
   849  
   850  	//copytx
   851  	crouptx1 := types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 460000000, Expire: 0, To: toAddr}
   852  	crouptx2 := types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 100, Expire: 0, To: toAddr}
   853  	crouptx3 := types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 100000000, Expire: 0, To: toAddr}
   854  	crouptx4 := types.Transaction{Execer: []byte("user.write"), Payload: types.Encode(transfer), Fee: 100000000, Expire: 0, To: toAddr}
   855  
   856  	txGroup, _ := types.CreateTxGroup([]*types.Transaction{&crouptx1, &crouptx2, &crouptx3, &crouptx4}, cfg.GetMinTxFeeRate())
   857  
   858  	for i := range txGroup.Txs {
   859  		err := txGroup.SignN(i, types.SECP256K1, mainPriv)
   860  		if err != nil {
   861  			t.Error("TestAddTxGroup SignNfailed ", err.Error())
   862  		}
   863  	}
   864  	tx := txGroup.Tx()
   865  
   866  	msg := mem.client.NewMessage("mempool", types.EventTx, tx)
   867  	mem.client.Send(msg, true)
   868  	resp, err := mem.client.Wait(msg)
   869  	if err != nil {
   870  		t.Error("TestAddTxGroup failed", err.Error())
   871  	}
   872  	reply := resp.GetData().(*types.Reply)
   873  	if !reply.GetIsOk() {
   874  		t.Error("TestAddTxGroup failed", string(reply.GetMsg()))
   875  	}
   876  }
   877  
   878  func TestLevelFeeBigByte(t *testing.T) {
   879  	q, mem := initEnv(0)
   880  	cfg := q.GetConfig()
   881  	defer q.Close()
   882  	defer mem.Close()
   883  	defer func() {
   884  		mem.cfg.IsLevelFee = false
   885  	}()
   886  	mem.cfg.IsLevelFee = true
   887  	mem.SetMinFee(100000)
   888  	msg0 := mem.client.NewMessage("mempool", types.EventTx, tx1)
   889  	mem.client.Send(msg0, true)
   890  	resp0, _ := mem.client.Wait(msg0)
   891  	if string(resp0.GetData().(*types.Reply).GetMsg()) != "" {
   892  		t.Error(string(resp0.GetData().(*types.Reply).GetMsg()))
   893  	}
   894  
   895  	msg00 := mem.client.NewMessage("mempool", types.EventTx, tx17)
   896  	mem.client.Send(msg00, true)
   897  	resp00, _ := mem.client.Wait(msg00)
   898  	if string(resp00.GetData().(*types.Reply).GetMsg()) != "" {
   899  		t.Error(string(resp00.GetData().(*types.Reply).GetMsg()))
   900  	}
   901  
   902  	msgBig1 := mem.client.NewMessage("mempool", types.EventTx, bigTx1)
   903  	mem.client.Send(msgBig1, true)
   904  	respBig1, _ := mem.client.Wait(msgBig1)
   905  	if string(respBig1.GetData().(*types.Reply).GetMsg()) != "" {
   906  		t.Error(string(respBig1.GetData().(*types.Reply).GetMsg()))
   907  	}
   908  
   909  	msgBig2 := mem.client.NewMessage("mempool", types.EventTx, bigTx2)
   910  	mem.client.Send(msgBig2, true)
   911  	respBig2, _ := mem.client.Wait(msgBig2)
   912  	if string(respBig2.GetData().(*types.Reply).GetMsg()) != "" {
   913  		t.Error(string(respBig2.GetData().(*types.Reply).GetMsg()))
   914  	}
   915  
   916  	msgBig3 := mem.client.NewMessage("mempool", types.EventTx, bigTx3)
   917  	mem.client.Send(msgBig3, true)
   918  	respBig3, _ := mem.client.Wait(msgBig3)
   919  	if string(respBig3.GetData().(*types.Reply).GetMsg()) != "" {
   920  		t.Error(string(respBig3.GetData().(*types.Reply).GetMsg()))
   921  	}
   922  
   923  	//test low fee , feeRate = 10 * minfee
   924  	msg2 := mem.client.NewMessage("mempool", types.EventTx, tx16)
   925  	mem.client.Send(msg2, true)
   926  	resp2, _ := mem.client.Wait(msg2)
   927  	if string(resp2.GetData().(*types.Reply).GetMsg()) != types.ErrTxFeeTooLow.Error() {
   928  		t.Error(string(resp2.GetData().(*types.Reply).GetMsg()))
   929  	}
   930  
   931  	//test high fee , feeRate = 10 * minfee
   932  	msg3 := mem.client.NewMessage("mempool", types.EventTx, tx6)
   933  	mem.client.Send(msg3, true)
   934  	resp3, _ := mem.client.Wait(msg3)
   935  	if string(resp3.GetData().(*types.Reply).GetMsg()) != "" {
   936  		t.Error(string(resp3.GetData().(*types.Reply).GetMsg()))
   937  	}
   938  
   939  	//test group high fee , feeRate = 10 * minfee
   940  	txGroup, err := types.CreateTxGroup([]*types.Transaction{bigTx4, bigTx5, bigTx6, bigTx7, bigTx8, bigTx9, bigTx10, bigTx11}, cfg.GetMinTxFeeRate())
   941  	if err != nil {
   942  		t.Error("CreateTxGroup err ", err.Error())
   943  	}
   944  	for i := range txGroup.Txs {
   945  		err := txGroup.SignN(i, types.SECP256K1, mainPriv)
   946  		if err != nil {
   947  			t.Error("TestAddTxGroup SignNfailed ", err.Error())
   948  		}
   949  	}
   950  	bigtxGroup := txGroup.Tx()
   951  
   952  	msgBigG := mem.client.NewMessage("mempool", types.EventTx, bigtxGroup)
   953  	mem.client.Send(msgBigG, true)
   954  	respBigG, _ := mem.client.Wait(msgBigG)
   955  	if string(respBigG.GetData().(*types.Reply).GetMsg()) != "" {
   956  		t.Error(string(respBigG.GetData().(*types.Reply).GetMsg()))
   957  	}
   958  
   959  	//test low fee , feeRate = 100 * minfee
   960  	msg4 := mem.client.NewMessage("mempool", types.EventTx, tx18)
   961  	mem.client.Send(msg4, true)
   962  	resp4, _ := mem.client.Wait(msg4)
   963  	if string(resp4.GetData().(*types.Reply).GetMsg()) != types.ErrTxFeeTooLow.Error() {
   964  		t.Error(string(resp4.GetData().(*types.Reply).GetMsg()))
   965  	}
   966  
   967  	//test high fee , feeRate = 100 * minfee
   968  	msg5 := mem.client.NewMessage("mempool", types.EventTx, tx8)
   969  	mem.client.Send(msg5, true)
   970  	resp5, _ := mem.client.Wait(msg5)
   971  	if string(resp5.GetData().(*types.Reply).GetMsg()) != "" {
   972  		t.Error(string(resp5.GetData().(*types.Reply).GetMsg()))
   973  	}
   974  }
   975  func TestLevelFeeTxNum(t *testing.T) {
   976  	q, mem := initEnv4(0)
   977  	defer q.Close()
   978  	defer mem.Close()
   979  	defer func() {
   980  		mem.cfg.IsLevelFee = false
   981  	}()
   982  	mem.cfg.IsLevelFee = true
   983  	mem.SetMinFee(100000)
   984  
   985  	//test low fee , feeRate = 10 * minfee
   986  	msg1 := mem.client.NewMessage("mempool", types.EventTx, tx16)
   987  	mem.client.Send(msg1, true)
   988  	resp1, _ := mem.client.Wait(msg1)
   989  	if string(resp1.GetData().(*types.Reply).GetMsg()) != types.ErrTxFeeTooLow.Error() {
   990  		t.Error(string(resp1.GetData().(*types.Reply).GetMsg()))
   991  	}
   992  
   993  	//test high fee , feeRate = 10 * minfee
   994  	msg2 := mem.client.NewMessage("mempool", types.EventTx, tx6)
   995  	mem.client.Send(msg2, true)
   996  	resp2, _ := mem.client.Wait(msg2)
   997  	if string(resp2.GetData().(*types.Reply).GetMsg()) != "" {
   998  		t.Error(string(resp2.GetData().(*types.Reply).GetMsg()))
   999  	}
  1000  
  1001  	//test high fee , feeRate = 10 * minfee
  1002  	msg3 := mem.client.NewMessage("mempool", types.EventTx, tx7)
  1003  	mem.client.Send(msg3, true)
  1004  	resp3, _ := mem.client.Wait(msg3)
  1005  	if string(resp3.GetData().(*types.Reply).GetMsg()) != "" {
  1006  		t.Error(string(resp3.GetData().(*types.Reply).GetMsg()))
  1007  	}
  1008  
  1009  	//test low fee , feeRate = 100 * minfee
  1010  	msg4 := mem.client.NewMessage("mempool", types.EventTx, tx18)
  1011  	mem.client.Send(msg4, true)
  1012  	resp4, _ := mem.client.Wait(msg4)
  1013  	if string(resp4.GetData().(*types.Reply).GetMsg()) != types.ErrTxFeeTooLow.Error() {
  1014  		t.Error(string(resp4.GetData().(*types.Reply).GetMsg()))
  1015  	}
  1016  
  1017  	//test high fee , feeRate = 100 * minfee
  1018  	msg5 := mem.client.NewMessage("mempool", types.EventTx, tx8)
  1019  	mem.client.Send(msg5, true)
  1020  	resp5, _ := mem.client.Wait(msg5)
  1021  	if string(resp5.GetData().(*types.Reply).GetMsg()) != "" {
  1022  		t.Error(string(resp5.GetData().(*types.Reply).GetMsg()))
  1023  	}
  1024  }
  1025  
  1026  func TestSimpleQueue_TotalFee(t *testing.T) {
  1027  	q, mem := initEnv(0)
  1028  	defer q.Close()
  1029  	defer mem.Close()
  1030  	txa := &types.Transaction{Payload: []byte("123"), Fee: 100000}
  1031  	mem.cache.Push(txa)
  1032  
  1033  	txb := &types.Transaction{Payload: []byte("1234"), Fee: 100000}
  1034  	mem.cache.Push(txb)
  1035  
  1036  	var sumFee int64
  1037  	mem.cache.Walk(mem.cache.Size(), func(it *Item) bool {
  1038  		sumFee += it.Value.Fee
  1039  		return true
  1040  	})
  1041  	require.Equal(t, sumFee, mem.cache.TotalFee())
  1042  	require.Equal(t, sumFee, int64(200000))
  1043  
  1044  	mem.cache.Remove(string(txb.Hash()))
  1045  
  1046  	var sumFee2 int64
  1047  	mem.cache.Walk(mem.cache.Size(), func(it *Item) bool {
  1048  		sumFee2 += it.Value.Fee
  1049  		return true
  1050  	})
  1051  	require.Equal(t, sumFee2, mem.cache.TotalFee())
  1052  	require.Equal(t, sumFee2, int64(100000))
  1053  }
  1054  
  1055  func TestSimpleQueue_TotalByte(t *testing.T) {
  1056  	q, mem := initEnv(0)
  1057  	defer q.Close()
  1058  	defer mem.Close()
  1059  	txa := &types.Transaction{Payload: []byte("123"), Fee: 100000}
  1060  	mem.cache.Push(txa)
  1061  
  1062  	txb := &types.Transaction{Payload: []byte("1234"), Fee: 100000}
  1063  	mem.cache.Push(txb)
  1064  
  1065  	var sumByte int64
  1066  	mem.cache.Walk(mem.cache.Size(), func(it *Item) bool {
  1067  		sumByte += int64(proto.Size(it.Value))
  1068  		return true
  1069  	})
  1070  	require.Equal(t, sumByte, mem.GetTotalCacheBytes())
  1071  	require.Equal(t, sumByte, int64(19))
  1072  
  1073  	mem.cache.Remove(string(txb.Hash()))
  1074  
  1075  	var sumByte2 int64
  1076  	mem.cache.Walk(mem.cache.Size(), func(it *Item) bool {
  1077  		sumByte2 += int64(proto.Size(it.Value))
  1078  		return true
  1079  	})
  1080  	require.Equal(t, sumByte2, mem.GetTotalCacheBytes())
  1081  	require.Equal(t, sumByte2, int64(9))
  1082  }
  1083  
  1084  func BenchmarkMempool(b *testing.B) {
  1085  	q, mem := initEnv(10240)
  1086  	defer q.Close()
  1087  	defer mem.Close()
  1088  	maxTxNumPerAccount = 100000
  1089  	for i := 0; i < b.N; i++ {
  1090  		to, _ := genaddress()
  1091  		tx := createTx(q.GetConfig(), mainPriv, to, 10000)
  1092  		msg := mem.client.NewMessage("mempool", types.EventTx, tx)
  1093  		err := mem.client.Send(msg, true)
  1094  		if err != nil {
  1095  			println(err)
  1096  		}
  1097  	}
  1098  	to0, _ := genaddress()
  1099  	tx0 := createTx(q.GetConfig(), mainPriv, to0, 10000)
  1100  	msg := mem.client.NewMessage("mempool", types.EventTx, tx0)
  1101  	mem.client.Send(msg, true)
  1102  	mem.client.Wait(msg)
  1103  	println(mem.Size() == b.N+1)
  1104  }
  1105  
  1106  func blockchainProcess(q queue.Queue) {
  1107  	dup := make(map[string]bool)
  1108  	go func() {
  1109  		client := q.Client()
  1110  		client.Sub("blockchain")
  1111  		for msg := range client.Recv() {
  1112  			if msg.Ty == types.EventGetLastHeader {
  1113  				msg.Reply(client.NewMessage("", types.EventHeader, &types.Header{Height: 1, BlockTime: 1}))
  1114  			} else if msg.Ty == types.EventIsSync {
  1115  				msg.Reply(client.NewMessage("", types.EventReplyIsSync, &types.IsCaughtUp{Iscaughtup: true}))
  1116  			} else if msg.Ty == types.EventTxHashList {
  1117  				txs := msg.Data.(*types.TxHashList)
  1118  				var hashlist [][]byte
  1119  				for _, hash := range txs.Hashes {
  1120  					if dup[string(hash)] {
  1121  						hashlist = append(hashlist, hash)
  1122  						continue
  1123  					}
  1124  					dup[string(hash)] = true
  1125  				}
  1126  				msg.Reply(client.NewMessage("consensus", types.EventTxHashListReply, &types.TxHashList{Hashes: hashlist}))
  1127  			}
  1128  		}
  1129  	}()
  1130  }
  1131  
  1132  func execProcess(q queue.Queue) {
  1133  	go func() {
  1134  		client := q.Client()
  1135  		client.Sub("execs")
  1136  		for msg := range client.Recv() {
  1137  			if msg.Ty == types.EventCheckTx {
  1138  				datas := msg.GetData().(*types.ExecTxList)
  1139  				result := &types.ReceiptCheckTxList{}
  1140  				for i := 0; i < len(datas.Txs); i++ {
  1141  					result.Errs = append(result.Errs, "")
  1142  				}
  1143  				msg.Reply(client.NewMessage("", types.EventReceiptCheckTx, result))
  1144  			}
  1145  		}
  1146  	}()
  1147  }
  1148  func TestTx(t *testing.T) {
  1149  	subConfig := SubConfig{10240, 10000}
  1150  	cache := newCache(10240, 10, 10240)
  1151  	cache.SetQueueCache(NewSimpleQueue(subConfig))
  1152  	tx := &types.Transaction{Execer: []byte("user.write"), Payload: types.Encode(transfer), Fee: 100000000, Expire: 0, To: toAddr}
  1153  
  1154  	var replyTxList types.ReplyTxList
  1155  	var sHastList types.ReqTxHashList
  1156  	var hastList types.ReqTxHashList
  1157  	for i := 1; i <= 10240; i++ {
  1158  		tx.Expire = int64(i)
  1159  		cache.Push(tx)
  1160  		sHastList.Hashes = append(sHastList.Hashes, types.CalcTxShortHash(tx.Hash()))
  1161  		hastList.Hashes = append(hastList.Hashes, string(tx.Hash()))
  1162  	}
  1163  
  1164  	for i := 1; i <= 1600; i++ {
  1165  		Tx := cache.GetSHashTxCache(sHastList.Hashes[i])
  1166  		if Tx == nil {
  1167  			panic("TestTx:GetSHashTxCache is nil")
  1168  		}
  1169  		replyTxList.Txs = append(replyTxList.Txs, Tx)
  1170  	}
  1171  
  1172  	for i := 1; i <= 1600; i++ {
  1173  		Tx := cache.getTxByHash(hastList.Hashes[i])
  1174  		if Tx == nil {
  1175  			panic("TestTx:getTxByHash is nil")
  1176  		}
  1177  		replyTxList.Txs = append(replyTxList.Txs, Tx)
  1178  	}
  1179  }
  1180  
  1181  func TestEventTxListByHash(t *testing.T) {
  1182  	q, mem := initEnv(0)
  1183  	defer q.Close()
  1184  	defer mem.Close()
  1185  
  1186  	// add tx
  1187  	hashes, err := add4TxHash(mem.client)
  1188  	if err != nil {
  1189  		t.Error("add tx error", err.Error())
  1190  		return
  1191  	}
  1192  	//通过交易hash获取交易信息
  1193  	reqTxHashList := types.ReqTxHashList{
  1194  		Hashes:      hashes,
  1195  		IsShortHash: false,
  1196  	}
  1197  	msg1 := mem.client.NewMessage("mempool", types.EventTxListByHash, &reqTxHashList)
  1198  	mem.client.Send(msg1, true)
  1199  	data1, err := mem.client.Wait(msg1)
  1200  	if err != nil {
  1201  		t.Error(err)
  1202  		return
  1203  	}
  1204  
  1205  	txs1 := data1.GetData().(*types.ReplyTxList).GetTxs()
  1206  
  1207  	if len(txs1) != 4 {
  1208  		t.Error("TestEventTxListByHash:get txlist number error")
  1209  	}
  1210  
  1211  	for i, tx := range txs1 {
  1212  		if hashes[i] != string(tx.Hash()) {
  1213  			t.Error("TestEventTxListByHash:hash mismatch")
  1214  		}
  1215  	}
  1216  
  1217  	//通过短hash获取tx交易
  1218  	var shashes []string
  1219  	for _, hash := range hashes {
  1220  		shashes = append(shashes, types.CalcTxShortHash([]byte(hash)))
  1221  	}
  1222  	reqTxHashList.Hashes = shashes
  1223  	reqTxHashList.IsShortHash = true
  1224  
  1225  	msg2 := mem.client.NewMessage("mempool", types.EventTxListByHash, &reqTxHashList)
  1226  	mem.client.Send(msg2, true)
  1227  	data2, err := mem.client.Wait(msg2)
  1228  	if err != nil {
  1229  		t.Error(err)
  1230  		return
  1231  	}
  1232  	txs2 := data2.GetData().(*types.ReplyTxList).GetTxs()
  1233  	for i, tx := range txs2 {
  1234  		if hashes[i] != string(tx.Hash()) {
  1235  			t.Error("TestEventTxListByHash:shash mismatch")
  1236  		}
  1237  	}
  1238  }
  1239  
  1240  //BenchmarkGetTxList-8   	    1000	   1631315 ns/op
  1241  func BenchmarkGetTxList(b *testing.B) {
  1242  
  1243  	q, mem := initEnv(0)
  1244  	defer q.Close()
  1245  	defer mem.Close()
  1246  
  1247  	txNum := 10000
  1248  	subConfig := SubConfig{int64(txNum), mem.cfg.MinTxFeeRate}
  1249  	mem.SetQueueCache(NewSimpleQueue(subConfig))
  1250  	mem.cache.AccountTxIndex.maxperaccount = txNum
  1251  	mem.cache.SHashTxCache.max = txNum
  1252  	cfg := q.GetConfig()
  1253  	for i := 0; i < txNum; i++ {
  1254  		tx := util.CreateCoinsTx(cfg, privKey, toAddr, int64(i+1))
  1255  		err := mem.PushTx(tx)
  1256  		require.Nil(b, err)
  1257  	}
  1258  	b.ResetTimer()
  1259  	for i := 0; i < b.N; i++ {
  1260  		mem.getTxList(&types.TxHashList{Hashes: nil, Count: int64(txNum)})
  1261  	}
  1262  }
  1263  
  1264  func TestGetTxList(t *testing.T) {
  1265  
  1266  	q, mem := initEnv(0)
  1267  	defer q.Close()
  1268  	defer mem.Close()
  1269  
  1270  	cacheSize := 100
  1271  	subConfig := SubConfig{int64(cacheSize), mem.cfg.MinTxFeeRate}
  1272  	mem.SetQueueCache(NewSimpleQueue(subConfig))
  1273  	mem.cache.AccountTxIndex.maxperaccount = cacheSize
  1274  	mem.cache.SHashTxCache.max = cacheSize
  1275  
  1276  	cfg := q.GetConfig()
  1277  	currentHeight := cfg.GetFork("ForkTxHeight")
  1278  	mem.setHeader(&types.Header{Height: currentHeight})
  1279  	//push expired invalid tx
  1280  	for i := 0; i < 10; i++ {
  1281  		tx := util.CreateNoneTxWithTxHeight(cfg, privKey, currentHeight+2+types.LowAllowPackHeight)
  1282  		require.True(t, tx.IsExpire(cfg, currentHeight+1, 0))
  1283  		err := mem.PushTx(tx)
  1284  		require.Nil(t, err)
  1285  	}
  1286  	// push unexpired valid tx
  1287  	for i := 0; i < 10; i++ {
  1288  		tx := util.CreateNoneTxWithTxHeight(cfg, privKey, currentHeight+1+types.LowAllowPackHeight)
  1289  		require.False(t, tx.IsExpire(cfg, currentHeight+1, 0))
  1290  		require.True(t, tx.IsExpire(cfg, currentHeight, 0))
  1291  		err := mem.PushTx(tx)
  1292  		require.Nil(t, err)
  1293  	}
  1294  
  1295  	// 取交易自动过滤过期交易
  1296  	txs := mem.getTxList(&types.TxHashList{Hashes: nil, Count: int64(5)})
  1297  	require.Equal(t, 5, len(txs))
  1298  	require.Equal(t, 20, mem.cache.Size())
  1299  	txs = mem.getTxList(&types.TxHashList{Hashes: nil, Count: int64(20)})
  1300  	require.Equal(t, 10, len(txs))
  1301  }
  1302  
  1303  func TestCheckTxsExist(t *testing.T) {
  1304  	q, mem := initEnv(0)
  1305  	defer q.Close()
  1306  	defer mem.Close()
  1307  
  1308  	txs := util.GenCoinsTxs(q.GetConfig(), privKey, 10)
  1309  	for _, tx := range txs {
  1310  		err := mem.PushTx(tx)
  1311  		require.Nil(t, err)
  1312  	}
  1313  	_, priv := util.Genaddress()
  1314  	txs1 := append(util.GenCoinsTxs(q.GetConfig(), priv, 10))
  1315  
  1316  	checkReq := &types.ReqCheckTxsExist{}
  1317  	// 构造请求数据,存在不存在交替
  1318  	for i, tx := range txs {
  1319  		checkReq.TxHashes = append(checkReq.TxHashes, tx.Hash(), txs1[i].Hash())
  1320  	}
  1321  	checkReqMsg := mem.client.NewMessage("mempool", types.EventCheckTxsExist, checkReq)
  1322  	mem.eventCheckTxsExist(checkReqMsg)
  1323  	reply, err := mem.client.Wait(checkReqMsg)
  1324  	require.Nil(t, err)
  1325  	replyData := reply.GetData().(*types.ReplyCheckTxsExist)
  1326  
  1327  	require.Equal(t, 20, len(replyData.ExistFlags))
  1328  	require.Equal(t, 10, int(replyData.ExistCount))
  1329  	for i, exist := range replyData.ExistFlags {
  1330  		//根据请求数据,结果应该是存在(true)、不存在(false)交替序列,即奇偶交错
  1331  		require.Equal(t, i%2 == 0, exist)
  1332  	}
  1333  	mem.setSync(false)
  1334  	mem.eventCheckTxsExist(checkReqMsg)
  1335  	reply, err = mem.client.Wait(checkReqMsg)
  1336  	require.Nil(t, err)
  1337  	replyData = reply.GetData().(*types.ReplyCheckTxsExist)
  1338  	require.Equal(t, 0, len(replyData.ExistFlags))
  1339  	require.Equal(t, 0, int(replyData.ExistCount))
  1340  }