github.com/aergoio/aergo@v1.3.1/polaris/server/mapservice_test.go (about)

     1  /*
     2   * @file
     3   * @copyright defined in aergo/LICENSE.txt
     4   */
     5  
     6  package server
     7  
     8  import (
     9  	"fmt"
    10  	"github.com/aergoio/aergo/p2p/p2pmock"
    11  	"github.com/aergoio/aergo/p2p/p2putil"
    12  	"github.com/libp2p/go-libp2p-core/network"
    13  	"reflect"
    14  	"sync"
    15  	"testing"
    16  	"time"
    17  
    18  	"github.com/aergoio/aergo/config"
    19  	"github.com/aergoio/aergo/p2p/p2pcommon"
    20  	"github.com/aergoio/aergo/pkg/component"
    21  	"github.com/aergoio/aergo/polaris/common"
    22  	"github.com/aergoio/aergo/types"
    23  	"github.com/golang/mock/gomock"
    24  	"github.com/golang/protobuf/proto"
    25  	"github.com/libp2p/go-libp2p-core/crypto"
    26  	"github.com/stretchr/testify/assert"
    27  )
    28  
    29  type dummyNTC struct {
    30  	nt      p2pcommon.NetworkTransport
    31  	self    p2pcommon.PeerMeta
    32  	chainID *types.ChainID
    33  }
    34  
    35  func (dntc *dummyNTC) SelfMeta() p2pcommon.PeerMeta {
    36  	return dntc.self
    37  }
    38  
    39  func (dntc *dummyNTC) GetNetworkTransport() p2pcommon.NetworkTransport {
    40  	return dntc.nt
    41  }
    42  func (dntc *dummyNTC) ChainID() *types.ChainID {
    43  	return dntc.chainID
    44  }
    45  
    46  var (
    47  	pmapDummyCfg = &config.Config{P2P: &config.P2PConfig{}, Polaris: &config.PolarisConfig{GenesisFile: "../../examples/genesis.json"},
    48  		Auth: &config.AuthConfig{EnableLocalConf: false}}
    49  	pmapDummyNTC = &dummyNTC{chainID: &types.ChainID{}}
    50  )
    51  
    52  func TestPeerMapService_BeforeStop(t *testing.T) {
    53  
    54  	type fields struct {
    55  		BaseComponent *component.BaseComponent
    56  		peerRegistry  map[types.PeerID]p2pcommon.PeerMeta
    57  	}
    58  	tests := []struct {
    59  		name   string
    60  		fields fields
    61  	}{
    62  		{"Tlisten", fields{}},
    63  		{"TNot", fields{}},
    64  		// TODO: Add test cases.
    65  	}
    66  	for _, tt := range tests {
    67  		t.Run(tt.name, func(t *testing.T) {
    68  			ctrl := gomock.NewController(t)
    69  
    70  			mockNT := p2pmock.NewMockNetworkTransport(ctrl)
    71  			pmapDummyNTC.nt = mockNT
    72  			pms := NewPolarisService(pmapDummyCfg, pmapDummyNTC)
    73  
    74  			mockNT.EXPECT().AddStreamHandler(common.PolarisMapSub, gomock.Any()).Times(1)
    75  			mockNT.EXPECT().RemoveStreamHandler(common.PolarisMapSub).Times(1)
    76  
    77  			pms.AfterStart()
    78  
    79  			pms.BeforeStop()
    80  
    81  			ctrl.Finish()
    82  		})
    83  	}
    84  }
    85  
    86  func TestPeerMapService_readRequest(t *testing.T) {
    87  	dummyMeta := p2pcommon.PeerMeta{ID: ""}
    88  	type args struct {
    89  		meta    p2pcommon.PeerMeta
    90  		readErr error
    91  	}
    92  	tests := []struct {
    93  		name string
    94  		args args
    95  
    96  		//want    p2p.Message
    97  		//want1   *types.MapQuery
    98  		wantErr bool
    99  	}{
   100  		{"TNormal", args{meta: dummyMeta, readErr: nil}, false},
   101  		{"TError", args{meta: dummyMeta, readErr: fmt.Errorf("testerr")}, true},
   102  	}
   103  	for _, tt := range tests {
   104  		t.Run(tt.name, func(t *testing.T) {
   105  			ctrl := gomock.NewController(t)
   106  			mockNT := p2pmock.NewMockNetworkTransport(ctrl)
   107  			pmapDummyNTC.nt = mockNT
   108  			mockNT.EXPECT().AddStreamHandler(common.PolarisMapSub, gomock.Any()).Times(1)
   109  
   110  			pms := NewPolarisService(pmapDummyCfg, pmapDummyNTC)
   111  			pms.AfterStart()
   112  
   113  			msgStub := &p2pcommon.MessageValue{}
   114  			mockRd := p2pmock.NewMockMsgReadWriter(ctrl)
   115  
   116  			mockRd.EXPECT().ReadMsg().Times(1).Return(msgStub, tt.args.readErr)
   117  
   118  			got, got1, err := pms.readRequest(tt.args.meta, mockRd)
   119  			if (err != nil) != tt.wantErr {
   120  				t.Errorf("PeerMapService.readRequest() error = %v, wantErr %v", err, tt.wantErr)
   121  				return
   122  			}
   123  			if !tt.wantErr {
   124  				if got == nil {
   125  					t.Errorf("PeerMapService.readRequest() got = %v, want %v", got, "not nil")
   126  				}
   127  				if got1 == nil {
   128  					t.Errorf("PeerMapService.readRequest() got = %v, want %v", got, "not nil")
   129  				}
   130  			}
   131  			//if !reflect.DeepEqual(got, tt.want) {
   132  			//	t.Errorf("PeerMapService.readRequest() got = %v, want %v", got, tt.want)
   133  			//}
   134  			//if !reflect.DeepEqual(got1, tt.want1) {
   135  			//	t.Errorf("PeerMapService.readRequest() got1 = %v, want %v", got1, tt.want1)
   136  			//}
   137  			ctrl.Finish()
   138  
   139  		})
   140  	}
   141  }
   142  
   143  func TestPeerMapService_handleQuery(t *testing.T) {
   144  	minVersion, _ := p2pcommon.ParseAergoVersion(p2pcommon.MinimumAergoVersion)
   145  	tooNewVersion, _ := p2pcommon.ParseAergoVersion(p2pcommon.MaximumAergoVersion)
   146  	tooOldVersion := minVersion
   147  	tooOldVersion.Patch = tooOldVersion.Patch-1
   148  	mainnetbytes, err := common.ONEMainNet.Bytes()
   149  	if err != nil {
   150  		t.Error("mainnet var is not set properly", common.ONEMainNet)
   151  	}
   152  	dummyPeerID2, err := types.IDB58Decode("16Uiu2HAmFqptXPfcdaCdwipB2fhHATgKGVFVPehDAPZsDKSU7jRm")
   153  
   154  	goodPeerMeta := p2pcommon.PeerMeta{ID: dummyPeerID2, IPAddress: "211.34.56.78", Port: 7845}
   155  	good := goodPeerMeta.ToPeerAddress()
   156  	badPeerMeta := p2pcommon.PeerMeta{ID: types.PeerID("bad"), IPAddress: "211.34.56.78", Port: 7845}
   157  	bad := badPeerMeta.ToPeerAddress()
   158  
   159  	ok := types.ResultStatus_OK
   160  
   161  	type args struct {
   162  		status *types.Status
   163  		addme  bool
   164  		size   int32
   165  	}
   166  	tests := []struct {
   167  		name string
   168  		args args
   169  
   170  		wantErr bool
   171  		wantMsg bool
   172  		wantStatus types.ResultStatus
   173  	}{
   174  		// check if parameter is bad
   175  		{"TMissingStat", args{nil, true, 9999}, true, false, ok},
   176  		// check if addMe is set or not
   177  		{"TOnlyQuery", args{&types.Status{ChainID: mainnetbytes, Sender: &good, Version:minVersion.String()}, false, 10}, false, false, ok},
   178  		{"TOnlyQuery2", args{&types.Status{ChainID: mainnetbytes, Sender: &bad, Version:minVersion.String()}, false, 10}, false, false, ok},
   179  		// TODO refator mapservice to run commented test
   180  		//{"TAddWithGood",args{&types.Status{ChainID:mainnetbytes, Sender:&good}, true, 10}, false, false, ok },
   181  		//{"TAddWithBad",args{&types.Status{ChainID:mainnetbytes, Sender:&bad}, true, 10}, false , true, ok },
   182  		// TODO: Add more cases .
   183  		// check if failed to connect back or not
   184  		{"TOldVersion", args{&types.Status{ChainID: mainnetbytes, Sender: &good, Version:tooOldVersion.String()}, false, 10}, false, true, types.ResultStatus_FAILED_PRECONDITION},
   185  		{"TNewVersion", args{&types.Status{ChainID: mainnetbytes, Sender: &good, Version:tooNewVersion.String()}, false, 10}, false, true, types.ResultStatus_FAILED_PRECONDITION},
   186  
   187  	}
   188  	for _, tt := range tests {
   189  		t.Run(tt.name, func(t *testing.T) {
   190  			ctrl := gomock.NewController(t)
   191  			mockNT := p2pmock.NewMockNetworkTransport(ctrl)
   192  			mockStream := p2pmock.NewMockStream(ctrl)
   193  			mockStream.EXPECT().Write(gomock.Any()).MaxTimes(1).Return(100, nil)
   194  			mockStream.EXPECT().Close().MaxTimes(1).Return(nil)
   195  			pmapDummyNTC.chainID = &common.ONEMainNet
   196  			pmapDummyNTC.nt = mockNT
   197  			mockNT.EXPECT().AddStreamHandler(gomock.Any(), gomock.Any())
   198  			mockNT.EXPECT().GetOrCreateStreamWithTTL(gomock.Any(), common.PolarisPingSub, gomock.Any()).Return(mockStream, nil)
   199  
   200  			pms := NewPolarisService(pmapDummyCfg, pmapDummyNTC)
   201  			pms.AfterStart()
   202  			query := &types.MapQuery{Status: tt.args.status, AddMe: tt.args.addme, Size: tt.args.size}
   203  
   204  			got, err := pms.handleQuery(nil, query)
   205  			if (err != nil) != tt.wantErr {
   206  				t.Errorf("PeerMapService.handleQuery() error = %v, wantErr %v", err, tt.wantErr)
   207  				return
   208  			}
   209  			if !tt.wantErr && (len(got.Message) > 0) != tt.wantMsg {
   210  				t.Errorf("PeerMapService.handleQuery() msg = %v, wantMsg %v", got.Message, tt.wantMsg)
   211  				return
   212  			}
   213  			if tt.wantMsg && got.Status != tt.wantStatus {
   214  				t.Errorf("PeerMapService.handleQuery() msg status = %v, want %v", got.Status.String(), tt.wantStatus.String())
   215  			}
   216  
   217  		})
   218  	}
   219  }
   220  
   221  var metas []p2pcommon.PeerMeta
   222  
   223  func init() {
   224  	metas = make([]p2pcommon.PeerMeta, 20)
   225  	for i := 0; i < 20; i++ {
   226  		_, pub, _ := crypto.GenerateKeyPair(crypto.Secp256k1, 256)
   227  		peerid, _ := types.IDFromPublicKey(pub)
   228  		metas[i] = p2pcommon.PeerMeta{ID: peerid}
   229  	}
   230  }
   231  
   232  func TestPeerMapService_registerPeer(t *testing.T) {
   233  	dupMetas := MakeMetaSlice(metas[2:5], metas[3:7])
   234  
   235  	tests := []struct {
   236  		name     string
   237  		args     []p2pcommon.PeerMeta
   238  		wantSize int
   239  		wantErr  bool
   240  	}{
   241  		{"TSingle", metas[:1], 1, false},
   242  		{"TMulti", metas[:5], 5, false},
   243  		{"TDup", dupMetas, 5, false},
   244  		{"TConcurrent", metas, 20, false},
   245  	}
   246  	for _, tt := range tests {
   247  		t.Run(tt.name, func(t *testing.T) {
   248  			ctrl := gomock.NewController(t)
   249  			mockNT := p2pmock.NewMockNetworkTransport(ctrl)
   250  			pms := NewPolarisService(pmapDummyCfg, pmapDummyNTC)
   251  			pms.nt = mockNT
   252  
   253  			wg := &sync.WaitGroup{}
   254  			finWg := &sync.WaitGroup{}
   255  			wg.Add(1)
   256  			finWg.Add(len(tt.args))
   257  			for _, meta := range tt.args {
   258  				go func(in p2pcommon.PeerMeta) {
   259  					wg.Wait()
   260  					pms.registerPeer(in)
   261  					finWg.Done()
   262  				}(meta)
   263  			}
   264  			wg.Done()
   265  			finWg.Wait()
   266  			assert.Equal(t, tt.wantSize, len(pms.peerRegistry))
   267  
   268  			ctrl.Finish()
   269  
   270  		})
   271  	}
   272  }
   273  
   274  func TestPeerMapService_unregisterPeer(t *testing.T) {
   275  	dupMetas := MakeMetaSlice(metas[2:5], metas[3:7])
   276  	allSize := len(metas)
   277  	tests := []struct {
   278  		name         string
   279  		args         []p2pcommon.PeerMeta
   280  		wantDecrease int
   281  		wantErr      bool
   282  	}{
   283  		{"TSingle", metas[:1], 1, false},
   284  		{"TMulti", metas[:5], 5, false},
   285  		{"TDup", dupMetas, 5, false},
   286  		{"TConcurrent", metas, 20, false},
   287  	}
   288  	for _, tt := range tests {
   289  		t.Run(tt.name, func(t *testing.T) {
   290  			ctrl := gomock.NewController(t)
   291  			mockNT := p2pmock.NewMockNetworkTransport(ctrl)
   292  			pms := NewPolarisService(pmapDummyCfg, pmapDummyNTC)
   293  			pms.nt = mockNT
   294  			for _, meta := range metas {
   295  				pms.registerPeer(meta)
   296  			}
   297  			wg := &sync.WaitGroup{}
   298  			finWg := &sync.WaitGroup{}
   299  			wg.Add(1)
   300  			finWg.Add(len(tt.args))
   301  			for _, meta := range tt.args {
   302  				go func(in p2pcommon.PeerMeta) {
   303  					wg.Wait()
   304  					pms.unregisterPeer(in.ID)
   305  					finWg.Done()
   306  				}(meta)
   307  			}
   308  			wg.Done()
   309  			finWg.Wait()
   310  			assert.Equal(t, allSize-tt.wantDecrease, len(pms.peerRegistry))
   311  
   312  			ctrl.Finish()
   313  
   314  		})
   315  	}
   316  }
   317  
   318  func MakeMetaSlice(slis ...[]p2pcommon.PeerMeta) []p2pcommon.PeerMeta {
   319  	result := make([]p2pcommon.PeerMeta, 0, 10)
   320  	for _, sli := range slis {
   321  		result = append(result, sli...)
   322  	}
   323  	return result
   324  }
   325  
   326  func TestPeerMapService_writeResponse(t *testing.T) {
   327  	type fields struct {
   328  		BaseComponent *component.BaseComponent
   329  		listen        bool
   330  		nt            p2pcommon.NetworkTransport
   331  		mutex         *sync.RWMutex
   332  		peerRegistry  map[types.PeerID]*peerState
   333  	}
   334  	type args struct {
   335  		reqContainer p2pcommon.Message
   336  		meta         p2pcommon.PeerMeta
   337  		resp         *types.MapResponse
   338  		wt           p2pcommon.MsgReadWriter
   339  	}
   340  	tests := []struct {
   341  		name    string
   342  		fields  fields
   343  		args    args
   344  		wantErr bool
   345  	}{
   346  		// TODO: Add test cases.
   347  	}
   348  	for _, tt := range tests {
   349  		t.Run(tt.name, func(t *testing.T) {
   350  			pms := &PeerMapService{
   351  				BaseComponent: tt.fields.BaseComponent,
   352  				nt:            tt.fields.nt,
   353  				rwmutex:       tt.fields.mutex,
   354  				peerRegistry:  tt.fields.peerRegistry,
   355  			}
   356  			if err := pms.writeResponse(tt.args.reqContainer, tt.args.meta, tt.args.resp, tt.args.wt); (err != nil) != tt.wantErr {
   357  				t.Errorf("PeerMapService.writeResponse() error = %v, wantErr %v", err, tt.wantErr)
   358  			}
   359  		})
   360  	}
   361  }
   362  
   363  func TestNewMapService(t *testing.T) {
   364  	type args struct {
   365  		cfg    *config.Config
   366  		ntc    p2pcommon.NTContainer
   367  		listen bool
   368  	}
   369  	tests := []struct {
   370  		name string
   371  		args args
   372  		want *PeerMapService
   373  	}{
   374  		// TODO: Add test cases.
   375  	}
   376  	for _, tt := range tests {
   377  		t.Run(tt.name, func(t *testing.T) {
   378  			if got := NewPolarisService(tt.args.cfg, tt.args.ntc); !reflect.DeepEqual(got, tt.want) {
   379  				t.Errorf("NewPolarisService() = %v, want %v", got, tt.want)
   380  			}
   381  		})
   382  	}
   383  }
   384  
   385  func TestPeerMapService_BeforeStart(t *testing.T) {
   386  	type fields struct {
   387  		BaseComponent *component.BaseComponent
   388  		ChainID       *types.ChainID
   389  		PrivateNet    bool
   390  		mapServers    []p2pcommon.PeerMeta
   391  		ntc           p2pcommon.NTContainer
   392  		listen        bool
   393  		nt            p2pcommon.NetworkTransport
   394  		hc            HealthCheckManager
   395  		rwmutex       *sync.RWMutex
   396  		peerRegistry  map[types.PeerID]*peerState
   397  	}
   398  	tests := []struct {
   399  		name   string
   400  		fields fields
   401  	}{
   402  		// TODO: Add test cases.
   403  	}
   404  	for _, tt := range tests {
   405  		t.Run(tt.name, func(t *testing.T) {
   406  			pms := &PeerMapService{
   407  				BaseComponent: tt.fields.BaseComponent,
   408  				PrivateNet:    tt.fields.PrivateNet,
   409  				ntc:           tt.fields.ntc,
   410  				nt:            tt.fields.nt,
   411  				hc:            tt.fields.hc,
   412  				rwmutex:       tt.fields.rwmutex,
   413  				peerRegistry:  tt.fields.peerRegistry,
   414  			}
   415  			pms.BeforeStart()
   416  		})
   417  	}
   418  }
   419  
   420  func TestPeerMapService_AfterStart(t *testing.T) {
   421  	type fields struct {
   422  		BaseComponent *component.BaseComponent
   423  		ChainID       *types.ChainID
   424  		PrivateNet    bool
   425  		mapServers    []p2pcommon.PeerMeta
   426  		ntc           p2pcommon.NTContainer
   427  		listen        bool
   428  		nt            p2pcommon.NetworkTransport
   429  		hc            HealthCheckManager
   430  		rwmutex       *sync.RWMutex
   431  		peerRegistry  map[types.PeerID]*peerState
   432  	}
   433  	tests := []struct {
   434  		name   string
   435  		fields fields
   436  	}{
   437  		// TODO: Add test cases.
   438  	}
   439  	for _, tt := range tests {
   440  		t.Run(tt.name, func(t *testing.T) {
   441  			pms := &PeerMapService{
   442  				BaseComponent: tt.fields.BaseComponent,
   443  				PrivateNet:    tt.fields.PrivateNet,
   444  				ntc:           tt.fields.ntc,
   445  				nt:            tt.fields.nt,
   446  				hc:            tt.fields.hc,
   447  				rwmutex:       tt.fields.rwmutex,
   448  				peerRegistry:  tt.fields.peerRegistry,
   449  			}
   450  			pms.AfterStart()
   451  		})
   452  	}
   453  }
   454  
   455  func TestPeerMapService_onConnect(t *testing.T) {
   456  	type fields struct {
   457  		BaseComponent *component.BaseComponent
   458  		ChainID       *types.ChainID
   459  		PrivateNet    bool
   460  		mapServers    []p2pcommon.PeerMeta
   461  		ntc           p2pcommon.NTContainer
   462  		listen        bool
   463  		nt            p2pcommon.NetworkTransport
   464  		hc            HealthCheckManager
   465  		rwmutex       *sync.RWMutex
   466  		peerRegistry  map[types.PeerID]*peerState
   467  	}
   468  	type args struct {
   469  		s network.Stream
   470  	}
   471  	tests := []struct {
   472  		name   string
   473  		fields fields
   474  		args   args
   475  	}{
   476  		// TODO: Add test cases.
   477  	}
   478  	for _, tt := range tests {
   479  		t.Run(tt.name, func(t *testing.T) {
   480  			pms := &PeerMapService{
   481  				BaseComponent: tt.fields.BaseComponent,
   482  				PrivateNet:    tt.fields.PrivateNet,
   483  				ntc:           tt.fields.ntc,
   484  				nt:            tt.fields.nt,
   485  				hc:            tt.fields.hc,
   486  				rwmutex:       tt.fields.rwmutex,
   487  				peerRegistry:  tt.fields.peerRegistry,
   488  			}
   489  			pms.onConnect(tt.args.s)
   490  		})
   491  	}
   492  }
   493  
   494  func TestPeerMapService_retrieveList(t *testing.T) {
   495  	type fields struct {
   496  		BaseComponent *component.BaseComponent
   497  		ChainID       *types.ChainID
   498  		PrivateNet    bool
   499  		mapServers    []p2pcommon.PeerMeta
   500  		ntc           p2pcommon.NTContainer
   501  		listen        bool
   502  		nt            p2pcommon.NetworkTransport
   503  		hc            HealthCheckManager
   504  		rwmutex       *sync.RWMutex
   505  		peerRegistry  map[types.PeerID]*peerState
   506  	}
   507  	type args struct {
   508  		maxPeers int
   509  		exclude  types.PeerID
   510  	}
   511  	tests := []struct {
   512  		name   string
   513  		fields fields
   514  		args   args
   515  		want   []*types.PeerAddress
   516  	}{
   517  		// TODO: Add test cases.
   518  	}
   519  	for _, tt := range tests {
   520  		t.Run(tt.name, func(t *testing.T) {
   521  			pms := &PeerMapService{
   522  				BaseComponent: tt.fields.BaseComponent,
   523  				PrivateNet:    tt.fields.PrivateNet,
   524  				ntc:           tt.fields.ntc,
   525  				nt:            tt.fields.nt,
   526  				hc:            tt.fields.hc,
   527  				rwmutex:       tt.fields.rwmutex,
   528  				peerRegistry:  tt.fields.peerRegistry,
   529  			}
   530  			if got := pms.retrieveList(tt.args.maxPeers, tt.args.exclude); !reflect.DeepEqual(got, tt.want) {
   531  				t.Errorf("PeerMapService.retrieveList() = %v, want %v", got, tt.want)
   532  			}
   533  		})
   534  	}
   535  }
   536  
   537  func Test_createV030Message(t *testing.T) {
   538  	type args struct {
   539  		msgID       p2pcommon.MsgID
   540  		orgID       p2pcommon.MsgID
   541  		subProtocol p2pcommon.SubProtocol
   542  		innerMsg    proto.Message
   543  	}
   544  	tests := []struct {
   545  		name    string
   546  		args    args
   547  		want    *p2pcommon.MessageValue
   548  		wantErr bool
   549  	}{
   550  		// TODO: Add test cases.
   551  	}
   552  	for _, tt := range tests {
   553  		t.Run(tt.name, func(t *testing.T) {
   554  			got, err := createV030Message(tt.args.msgID, tt.args.orgID, tt.args.subProtocol, tt.args.innerMsg)
   555  			if (err != nil) != tt.wantErr {
   556  				t.Errorf("createV030Message() error = %v, wantErr %v", err, tt.wantErr)
   557  				return
   558  			}
   559  			if !reflect.DeepEqual(got, tt.want) {
   560  				t.Errorf("createV030Message() = %v, want %v", got, tt.want)
   561  			}
   562  		})
   563  	}
   564  }
   565  
   566  func TestPeerMapService_getPeerCheckers(t *testing.T) {
   567  	type fields struct {
   568  		BaseComponent *component.BaseComponent
   569  		ChainID       *types.ChainID
   570  		PrivateNet    bool
   571  		mapServers    []p2pcommon.PeerMeta
   572  		ntc           p2pcommon.NTContainer
   573  		listen        bool
   574  		nt            p2pcommon.NetworkTransport
   575  		hc            HealthCheckManager
   576  		rwmutex       *sync.RWMutex
   577  		peerRegistry  map[types.PeerID]*peerState
   578  	}
   579  	tests := []struct {
   580  		name   string
   581  		fields fields
   582  		want   []peerChecker
   583  	}{
   584  		// TODO: Add test cases.
   585  	}
   586  	for _, tt := range tests {
   587  		t.Run(tt.name, func(t *testing.T) {
   588  			pms := &PeerMapService{
   589  				BaseComponent: tt.fields.BaseComponent,
   590  				PrivateNet:    tt.fields.PrivateNet,
   591  				ntc:           tt.fields.ntc,
   592  				nt:            tt.fields.nt,
   593  				hc:            tt.fields.hc,
   594  				rwmutex:       tt.fields.rwmutex,
   595  				peerRegistry:  tt.fields.peerRegistry,
   596  			}
   597  			if got := pms.getPeerCheckers(); !reflect.DeepEqual(got, tt.want) {
   598  				t.Errorf("PeerMapService.getPeerCheckers() = %v, want %v", got, tt.want)
   599  			}
   600  		})
   601  	}
   602  }
   603  
   604  func TestPeerMapService_applyNewBLEntry(t *testing.T) {
   605  	id1, _ := types.IDB58Decode("16Uiu2HAmPZE7gT1hF2bjpg1UVH65xyNUbBVRf3mBFBJpz3tgLGGt")
   606  	id2 := p2putil.RandomPeerID()
   607  	id3 := p2putil.RandomPeerID()
   608  	ad10 := "123.45.67.89"
   609  	ad11 := "123.45.67.91" // same C class network
   610  	ad2 := "2001:0db8:0123:4567:89ab:cdef:1234:5678"
   611  	ad3 := "222.8.8.8"
   612  	m10 := p2pcommon.PeerMeta{IPAddress: ad10, ID: id1}
   613  	m11 := p2pcommon.PeerMeta{IPAddress: ad10, ID: p2putil.RandomPeerID()}
   614  	m12 := p2pcommon.PeerMeta{IPAddress: ad11, ID: p2putil.RandomPeerID()}
   615  	m2 := p2pcommon.PeerMeta{IPAddress: ad2, ID: id2}
   616  	m3 := p2pcommon.PeerMeta{IPAddress: ad3, ID: id3}
   617  
   618  	type args struct {
   619  		entry types.WhiteListEntry
   620  	}
   621  	tests := []struct {
   622  		name string
   623  		args args
   624  
   625  		wantDeleted []p2pcommon.PeerMeta
   626  	}{
   627  		{"IDOnly", args{wle(`{"peerid":"16Uiu2HAmPZE7gT1hF2bjpg1UVH65xyNUbBVRf3mBFBJpz3tgLGGt"}`)}, mm(m10)},
   628  		{"IDOnlyNotFound", args{wle(`{"peerid":"16Uiu2HAkvvhjxVm2WE9yFBDdPQ9qx6pX9taF6TTwDNHs8VPi1EeR"}`)}, mm()},
   629  		{"AddrOnly", args{wle(`{"address":"123.45.67.89"}`)}, mm(m10, m11)},
   630  		{"AddrRange", args{wle(`{"peerid":"", "cidr":"123.45.67.89/24"}`)}, mm(m10, m11, m12)},
   631  		{"IDAddr", args{wle(`{"peerid":"16Uiu2HAmPZE7gT1hF2bjpg1UVH65xyNUbBVRf3mBFBJpz3tgLGGt", "address":"123.45.67.89"}`)}, mm(m10)},
   632  		{"IDAddrNotFound", args{wle(`{"peerid":"16Uiu2HAmPZE7gT1hF2bjpg1UVH65xyNUbBVRf3mBFBJpz3tgLGGt", "address":"122.1.3.4"}`)}, mm()},
   633  		{"IDAdRange24", args{wle(`{"peerid":"16Uiu2HAmPZE7gT1hF2bjpg1UVH65xyNUbBVRf3mBFBJpz3tgLGGt", "cidr":"123.45.67.1/24"}`)}, mm(m10)},
   634  	}
   635  	for _, tt := range tests {
   636  		t.Run(tt.name, func(t *testing.T) {
   637  			ctrl := gomock.NewController(t)
   638  			defer ctrl.Finish()
   639  
   640  			mockNT := p2pmock.NewMockNetworkTransport(ctrl)
   641  			pmapDummyNTC.nt = mockNT
   642  			pms := NewPolarisService(pmapDummyCfg, pmapDummyNTC)
   643  			// add sample peers
   644  			for _, m := range mm(m10, m11, m12, m2, m3) {
   645  				pms.peerRegistry[m.ID] = &peerState{PeerMapService: pms, meta: m, addr: m.ToPeerAddress(), lCheckTime: time.Now(), temporary: false}
   646  			}
   647  			prevLen := len(pms.peerRegistry)
   648  			pms.applyNewBLEntry(tt.args.entry)
   649  
   650  			if len(pms.peerRegistry) != (prevLen - len(tt.wantDeleted)) {
   651  				t.Errorf("applyNewBLEntry() %v remains, want %v", len(pms.peerRegistry), prevLen-len(tt.wantDeleted))
   652  			}
   653  			for _, m := range tt.wantDeleted {
   654  				if _, found := pms.peerRegistry[m.ID]; found {
   655  					t.Errorf("applyNewBLEntry() peer %v exist, want deleted", p2putil.ShortForm(m.ID))
   656  				}
   657  			}
   658  		})
   659  	}
   660  }
   661  
   662  func wle(str string) types.WhiteListEntry {
   663  	ent, err := types.ParseListEntry(str)
   664  	if err != nil {
   665  		panic("invalid input : " + str + " : " + err.Error())
   666  	}
   667  	return ent
   668  }
   669  
   670  func mm(metas ...p2pcommon.PeerMeta) []p2pcommon.PeerMeta {
   671  	return metas
   672  }
   673  
   674  func TestPeerMapService_onConnectWithBlacklist(t *testing.T) {
   675  	d0 := "{\"address\":\"172.21.3.35\",\"cidr\":\"\",\"peerid\":\"16Uiu2HAmPZE7gT1hF2bjpg1UVH65xyNUbBVRf3mBFBJpz3tgLGGt\"}"
   676  	d1 := "{\"address\":\"\",\"cidr\":\"172.21.0.0/16\",\"peerid\":\"16Uiu2HAmPZE7gT1hF2bjpg1UVH65xyNUbBVRf3mBFBJpz3tgLGGt\"}"
   677  	d2 := "{\"address\":\"0.0.0.0\",\"cidr\":\"\",\"peerid\":\"16Uiu2HAmPZE7gT1hF2bjpg1UVH65xyNUbBVRf3mBFBJpz3tgLGGt\"}"
   678  	d3 := "{\"address\":\"\",\"cidr\":\"172.21.0.0/16\",\"peerid\":\"\"}"
   679  	d4 := "{\"address\":\"2001:db8:123:4567:89ab:cdef:1234:5678\",\"cidr\":\"\",\"peerid\":\"\"}"
   680  	d5 := "{\"address\":\"0.0.0.0\",\"cidr\":\"\",\"peerid\":\"\"}"
   681  	d6 := "{\"address\":\"\",\"cidr\":\"2001:db8:123:4567:89ab:cdef::/96\",\"peerid\":\"\"}"
   682  	entries := []types.WhiteListEntry{}
   683  	for _, d := range []string{d0, d1, d2, d3, d4, d5, d6} {
   684  		e, _ := types.ParseListEntry(d)
   685  		entries = append(entries, e)
   686  	}
   687  
   688  	type args struct {
   689  		s types.Stream
   690  	}
   691  	tests := []struct {
   692  		name   string
   693  		args   args
   694  	}{
   695  		// TODO: Add test cases.
   696  	}
   697  	for _, tt := range tests {
   698  		t.Run(tt.name, func(t *testing.T) {
   699  			ctrl := gomock.NewController(t)
   700  			defer ctrl.Finish()
   701  
   702  			mockNT := p2pmock.NewMockNetworkTransport(ctrl)
   703  
   704  			pmapDummyNTC.nt = mockNT
   705  			pms := NewPolarisService(pmapDummyCfg, pmapDummyNTC)
   706  			for _, e := range entries {
   707  				pms.lm.AddEntry(e)
   708  			}
   709  
   710  			pms.onConnect(tt.args.s)
   711  		})
   712  	}
   713  }