github.com/turingchain2020/turingchain@v1.1.21/system/p2p/dht/protocol/broadcast/broadcast_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 broadcast
     6  
     7  import (
     8  	"context"
     9  	"crypto/rand"
    10  	"encoding/hex"
    11  	"fmt"
    12  	"testing"
    13  
    14  	net "github.com/turingchain2020/turingchain/system/p2p/dht/extension"
    15  	"github.com/libp2p/go-libp2p"
    16  	core "github.com/libp2p/go-libp2p-core"
    17  	"github.com/libp2p/go-libp2p-core/crypto"
    18  	"github.com/multiformats/go-multiaddr"
    19  
    20  	"github.com/turingchain2020/turingchain/client"
    21  	commlog "github.com/turingchain2020/turingchain/common/log"
    22  	"github.com/turingchain2020/turingchain/p2p"
    23  	"github.com/turingchain2020/turingchain/queue"
    24  	prototypes "github.com/turingchain2020/turingchain/system/p2p/dht/protocol"
    25  	p2pty "github.com/turingchain2020/turingchain/system/p2p/dht/types"
    26  	"github.com/turingchain2020/turingchain/types"
    27  	"github.com/libp2p/go-libp2p-core/peer"
    28  	"github.com/stretchr/testify/assert"
    29  )
    30  
    31  func init() {
    32  	commlog.SetLogLevel("error")
    33  }
    34  
    35  var (
    36  	payload = []byte("testpayload")
    37  	minerTx = &types.Transaction{Execer: []byte("coins"), Payload: payload, Fee: 14600, Expire: 200}
    38  	tx      = &types.Transaction{Execer: []byte("coins"), Payload: payload, Fee: 4600, Expire: 2}
    39  	tx1     = &types.Transaction{Execer: []byte("coins"), Payload: payload, Fee: 460000000, Expire: 0}
    40  	tx2     = &types.Transaction{Execer: []byte("coins"), Payload: payload, Fee: 100, Expire: 1}
    41  	txList  = append([]*types.Transaction{}, minerTx, tx, tx1, tx2)
    42  
    43  	testBlock = &types.Block{
    44  		TxHash: []byte("test"),
    45  		Height: 10,
    46  		Txs:    txList,
    47  	}
    48  	testAddr   = "testPeerAddr"
    49  	testPidStr = "16Uiu2HAm14hiGBFyFChPdG98RaNAMtcFJmgZjEQLuL87xsSkv72U"
    50  	testPid, _ = peer.Decode("16Uiu2HAm14hiGBFyFChPdG98RaNAMtcFJmgZjEQLuL87xsSkv72U")
    51  )
    52  
    53  func newHost(port int32) core.Host {
    54  	priv, _, _ := crypto.GenerateKeyPairWithReader(crypto.RSA, 2048, rand.Reader)
    55  	m, err := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/0.0.0.0/tcp/%d", port))
    56  	if err != nil {
    57  		return nil
    58  	}
    59  
    60  	host, err := libp2p.New(context.Background(),
    61  		libp2p.ListenAddrs(m),
    62  		libp2p.Identity(priv),
    63  	)
    64  
    65  	if err != nil {
    66  		panic(err)
    67  	}
    68  
    69  	return host
    70  }
    71  
    72  func newTestEnv(q queue.Queue) *prototypes.P2PEnv {
    73  	cfg := types.NewTuringchainConfig(types.ReadFile("../../../../../cmd/turingchain/turingchain.test.toml"))
    74  	q.SetConfig(cfg)
    75  	go q.Start()
    76  
    77  	mgr := p2p.NewP2PMgr(cfg)
    78  	mgr.Client = q.Client()
    79  	mgr.SysAPI, _ = client.New(mgr.Client, nil)
    80  
    81  	subCfg := &p2pty.P2PSubConfig{}
    82  	types.MustDecode(cfg.GetSubConfig().P2P[p2pty.DHTTypeName], subCfg)
    83  	env := &prototypes.P2PEnv{
    84  		ChainCfg:        cfg,
    85  		QueueClient:     q.Client(),
    86  		Host:            newHost(13902),
    87  		ConnManager:     nil,
    88  		PeerInfoManager: nil,
    89  		P2PManager:      mgr,
    90  		SubConfig:       subCfg,
    91  		Ctx:             context.Background(),
    92  	}
    93  	env.Pubsub, _ = net.NewPubSub(env.Ctx, env.Host)
    94  	return env
    95  }
    96  
    97  func newTestProtocolWithQueue(q queue.Queue) *broadcastProtocol {
    98  	env := newTestEnv(q)
    99  	prototypes.ClearEventHandler()
   100  	p := &broadcastProtocol{}
   101  	p.init(env)
   102  	return p
   103  }
   104  
   105  func newTestProtocol() *broadcastProtocol {
   106  
   107  	q := queue.New("test")
   108  	return newTestProtocolWithQueue(q)
   109  }
   110  
   111  func TestBroadCastProtocol_InitProtocol(t *testing.T) {
   112  
   113  	protocol := newTestProtocol()
   114  	assert.Equal(t, defaultMinLtBlockSize, int(protocol.p2pCfg.MinLtBlockSize))
   115  	assert.Equal(t, defaultLtTxBroadCastTTL, int(protocol.p2pCfg.LightTxTTL))
   116  }
   117  
   118  func testHandleEvent(protocol *broadcastProtocol, msg *queue.Message) {
   119  
   120  	defer func() {
   121  		if r := recover(); r != nil {
   122  		}
   123  	}()
   124  
   125  	protocol.handleBroadCastEvent(msg)
   126  }
   127  
   128  func TestBroadCastEvent(t *testing.T) {
   129  	protocol := newTestProtocol()
   130  	msgs := make([]*queue.Message, 0)
   131  	msgs = append(msgs, protocol.QueueClient.NewMessage("p2p", types.EventTxBroadcast, &types.Transaction{}))
   132  	msgs = append(msgs, protocol.QueueClient.NewMessage("p2p", types.EventBlockBroadcast, &types.Block{}))
   133  	msgs = append(msgs, protocol.QueueClient.NewMessage("p2p", types.EventTx, &types.LightTx{}))
   134  
   135  	for _, msg := range msgs {
   136  		testHandleEvent(protocol, msg)
   137  	}
   138  	_, ok := protocol.txFilter.Get(hex.EncodeToString((&types.Transaction{}).Hash()))
   139  	assert.True(t, ok)
   140  	_, ok = protocol.blockFilter.Get(hex.EncodeToString((&types.Block{}).Hash(protocol.ChainCfg)))
   141  	assert.True(t, ok)
   142  }
   143  
   144  func Test_util(t *testing.T) {
   145  	proto := newTestProtocol()
   146  	exist := addIgnoreSendPeerAtomic(proto.txSendFilter, "hash", "pid1")
   147  	assert.False(t, exist)
   148  	exist = addIgnoreSendPeerAtomic(proto.txSendFilter, "hash", "pid2")
   149  	assert.False(t, exist)
   150  	exist = addIgnoreSendPeerAtomic(proto.txSendFilter, "hash", "pid1")
   151  	assert.True(t, exist)
   152  }