github.com/aergoio/aergo@v1.3.1/p2p/transport/networktransport_test.go (about)

     1  /*
     2   * @file
     3   * @copyright defined in aergo/LICENSE.txt
     4   */
     5  
     6  package transport
     7  
     8  import (
     9  	"encoding/hex"
    10  	"testing"
    11  	"time"
    12  
    13  	"github.com/aergoio/aergo-lib/log"
    14  	"github.com/aergoio/aergo/config"
    15  	cfg "github.com/aergoio/aergo/config"
    16  	"github.com/aergoio/aergo/message"
    17  	"github.com/aergoio/aergo/p2p/p2pcommon"
    18  	"github.com/aergoio/aergo/p2p/p2pkey"
    19  	"github.com/aergoio/aergo/p2p/p2pmock"
    20  	"github.com/aergoio/aergo/types"
    21  	"github.com/golang/mock/gomock"
    22  )
    23  
    24  const (
    25  	sampleKeyFile = "../../test/sample.key"
    26  )
    27  
    28  func init() {
    29  	//sampleID := "16Uiu2HAmP2iRDpPumUbKhNnEngoxAUQWBmCyn7FaYUrkaDAMXJPJ"
    30  	baseCfg := &config.BaseConfig{AuthDir: "test"}
    31  	p2pCfg := &config.P2PConfig{NPKey: sampleKeyFile}
    32  	p2pkey.InitNodeInfo(baseCfg, p2pCfg, "0.0.1-test", log.NewLogger("test.transport"))
    33  }
    34  
    35  // TODO split this test into two... one is to attempt make connection and the other is test peermanager if same peerid is given
    36  // Ignoring test for now, for lack of abstraction on AergoPeer struct
    37  func IgnoredTestP2PServiceRunAddPeer(t *testing.T) {
    38  	var sampleBlockHash, _ = hex.DecodeString("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac")
    39  	var sampleBlockHeight uint64 = 100215
    40  
    41  	ctrl := gomock.NewController(t)
    42  	defer ctrl.Finish()
    43  
    44  	mockActor := p2pmock.NewMockActorService(ctrl)
    45  	dummyBlock := types.Block{Hash: sampleBlockHash, Header: &types.BlockHeader{BlockNo: sampleBlockHeight}}
    46  	mockActor.EXPECT().CallRequest(gomock.Any(), gomock.Any(), gomock.Any()).Return(message.GetBlockRsp{Block: &dummyBlock}, nil)
    47  	//mockMF := new(MockMoFactory)
    48  	target := &networkTransport{conf: config.NewServerContext("", "").GetDefaultConfig().(*config.Config).P2P,
    49  		logger: log.NewLogger("test.p2p")}
    50  
    51  	//target.Host = &mockHost{peerstore.NewPeerstore(pstoremem.NewKeyBook(), pstoremem.NewAddrBook(), pstoremem.NewPeerMetadata())}
    52  	target.Host = p2pmock.NewMockHost(ctrl)
    53  	target.selfMeta.ID = types.PeerID("gwegw")
    54  
    55  	sampleAddr1 := p2pcommon.PeerMeta{ID: "ddd", IPAddress: "192.168.0.1", Port: 33888, Outbound: true}
    56  	sampleAddr2 := p2pcommon.PeerMeta{ID: "fff", IPAddress: "192.168.0.2", Port: 33888, Outbound: true}
    57  	target.GetOrCreateStream(sampleAddr1, p2pcommon.LegacyP2PSubAddr)
    58  	target.GetOrCreateStream(sampleAddr1, p2pcommon.LegacyP2PSubAddr)
    59  	time.Sleep(time.Second)
    60  	if len(target.Peerstore().Peers()) != 1 {
    61  		t.Errorf("Peer count : Expected %d, Actually %d", 1, len(target.Peerstore().Peers()))
    62  	}
    63  	target.GetOrCreateStream(sampleAddr2, p2pcommon.LegacyP2PSubAddr)
    64  	time.Sleep(time.Second * 1)
    65  	if len(target.Peerstore().Peers()) != 2 {
    66  		t.Errorf("Peer count : Expected %d, Actually %d", 2, len(target.Peerstore().Peers()))
    67  	}
    68  }
    69  
    70  func TestNewNetworkTransport(t *testing.T) {
    71  	logger := log.NewLogger("test.transport")
    72  	svrctx := config.NewServerContext("", "")
    73  	sampleIP := "211.1.2.3"
    74  
    75  	tests := []struct {
    76  		name string
    77  
    78  		protocolAddr string
    79  		bindAddr     string
    80  		protocolPort int
    81  		bindPort     int
    82  		wantAddress  string
    83  		wantPort     uint32
    84  	}{
    85  		{"TDefault", sampleIP, "", -1, -1, sampleIP, 7846},
    86  		{"TAddrProto", sampleIP, "", -1, -1, sampleIP, 7846},
    87  		{"TAddrBind", sampleIP, sampleIP, -1, -1, sampleIP, 7846},
    88  		{"TAddrDiffer", "123.45.67.89", sampleIP, -1, -1, sampleIP, 7846},
    89  	}
    90  	for _, tt := range tests {
    91  		t.Run(tt.name, func(t *testing.T) {
    92  			ctrl := gomock.NewController(t)
    93  			defer ctrl.Finish()
    94  
    95  			sampleMeta := p2pcommon.PeerMeta{IPAddress: tt.protocolAddr, Port: 7846, ID: p2pkey.NodeID()}
    96  			conf := svrctx.GetDefaultP2PConfig()
    97  			if len(tt.protocolAddr) > 0 {
    98  				sampleMeta.IPAddress = tt.protocolAddr
    99  			}
   100  			if len(tt.bindAddr) > 0 {
   101  				conf.NPBindAddr = tt.bindAddr
   102  			}
   103  			if tt.protocolPort > 0 {
   104  				sampleMeta.Port = uint32(tt.protocolPort)
   105  			}
   106  			if tt.bindPort > 0 {
   107  				conf.NPBindPort = tt.bindPort
   108  			}
   109  			mockIS := p2pmock.NewMockInternalService(ctrl)
   110  			mockIS.EXPECT().SelfMeta().Return(sampleMeta)
   111  			got := NewNetworkTransport(conf, logger, mockIS)
   112  
   113  			if got.privateKey == nil {
   114  				t.Errorf("NewNetworkTransport() privkey is nil, want not")
   115  			}
   116  
   117  			addr := got.bindAddress
   118  			port := got.bindPort
   119  			if addr != tt.wantAddress {
   120  				t.Errorf("initServiceBindAddress() addr = %v, want %v", addr, tt.wantAddress)
   121  			}
   122  			if port != tt.wantPort {
   123  				t.Errorf("initServiceBindAddress() port = %v, want %v", port, tt.wantPort)
   124  			}
   125  
   126  		})
   127  	}
   128  }
   129  
   130  func Test_networkTransport_initServiceBindAddress(t *testing.T) {
   131  	logger := log.NewLogger("test.transport")
   132  	svrctx := config.NewServerContext("", "")
   133  	initialPort := uint32(7846)
   134  	sampleIP := "203.1.2.111"
   135  	sampleDomain := "unittest.aergo.io"
   136  	ipMeta := p2pcommon.PeerMeta{IPAddress: sampleIP, Port: initialPort}
   137  	dnMeta := p2pcommon.PeerMeta{IPAddress: sampleDomain, Port: initialPort}
   138  	tests := []struct {
   139  		name string
   140  		meta p2pcommon.PeerMeta
   141  		conf *cfg.P2PConfig
   142  
   143  		wantAddress string
   144  		wantPort    uint32
   145  	}{
   146  		{"TEmpty", ipMeta, svrctx.GetDefaultP2PConfig(), sampleIP, initialPort},
   147  		{"TAnywhere", ipMeta, withAddr(svrctx.GetDefaultP2PConfig(), "0.0.0.0"), "0.0.0.0", initialPort},
   148  		{"TAnywhereDN", dnMeta, withAddr(svrctx.GetDefaultP2PConfig(), "0.0.0.0"), "0.0.0.0", initialPort},
   149  		{"TLoopbackDN", dnMeta, withAddr(svrctx.GetDefaultP2PConfig(), "127.0.0.1"), "127.0.0.1", initialPort},
   150  		{"TCustAddr", ipMeta, withAddr(svrctx.GetDefaultP2PConfig(), "211.1.2.3"), "211.1.2.3", initialPort},
   151  		{"TCustAddrPort", ipMeta, withPort(withAddr(svrctx.GetDefaultP2PConfig(), "211.1.2.3"), 7777), "211.1.2.3", 7777},
   152  		// TODO: Add test cases.
   153  	}
   154  	for _, tt := range tests {
   155  		t.Run(tt.name, func(t *testing.T) {
   156  			sl := &networkTransport{conf: tt.conf,
   157  				logger:   logger,
   158  				bindPort: uint32(initialPort),
   159  				selfMeta:tt.meta,
   160  			}
   161  			sl.initServiceBindAddress()
   162  
   163  			addr := sl.bindAddress
   164  			port := sl.bindPort
   165  			// init result must always bind valid address
   166  			if addr != tt.wantAddress {
   167  				t.Errorf("initServiceBindAddress() addr = %v, want %v", addr, tt.wantAddress)
   168  			}
   169  			if port != tt.wantPort {
   170  				t.Errorf("initServiceBindAddress() port = %v, want %v", port, tt.wantPort)
   171  			}
   172  		})
   173  	}
   174  }
   175  
   176  func withAddr(conf *cfg.P2PConfig, addr string) *cfg.P2PConfig {
   177  	conf.NPBindAddr = addr
   178  	return conf
   179  }
   180  
   181  func withPort(conf *cfg.P2PConfig, port int) *cfg.P2PConfig {
   182  	conf.NPBindPort = port
   183  	return conf
   184  }