github.com/myafeier/fabric@v1.0.1-0.20170722181825-3a4b1f2bce86/gossip/service/gossip_service_test.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package service
     8  
     9  import (
    10  	"bytes"
    11  	"fmt"
    12  	"net"
    13  	"sync"
    14  	"testing"
    15  	"time"
    16  
    17  	"github.com/hyperledger/fabric/common/config"
    18  	"github.com/hyperledger/fabric/common/localmsp"
    19  	"github.com/hyperledger/fabric/core/deliverservice"
    20  	"github.com/hyperledger/fabric/core/deliverservice/blocksprovider"
    21  	"github.com/hyperledger/fabric/gossip/api"
    22  	gossipCommon "github.com/hyperledger/fabric/gossip/common"
    23  	"github.com/hyperledger/fabric/gossip/election"
    24  	"github.com/hyperledger/fabric/gossip/gossip"
    25  	"github.com/hyperledger/fabric/gossip/identity"
    26  	"github.com/hyperledger/fabric/gossip/state"
    27  	"github.com/hyperledger/fabric/gossip/util"
    28  	"github.com/hyperledger/fabric/msp/mgmt"
    29  	"github.com/hyperledger/fabric/msp/mgmt/testtools"
    30  	peergossip "github.com/hyperledger/fabric/peer/gossip"
    31  	"github.com/hyperledger/fabric/peer/gossip/mocks"
    32  	"github.com/hyperledger/fabric/protos/common"
    33  	"github.com/hyperledger/fabric/protos/peer"
    34  	"github.com/spf13/viper"
    35  	"github.com/stretchr/testify/assert"
    36  	"google.golang.org/grpc"
    37  )
    38  
    39  func init() {
    40  	util.SetupTestLogging()
    41  }
    42  
    43  func TestInitGossipService(t *testing.T) {
    44  	// Test whenever gossip service is indeed singleton
    45  	grpcServer := grpc.NewServer()
    46  	socket, error := net.Listen("tcp", fmt.Sprintf("%s:%d", "", 5611))
    47  	assert.NoError(t, error)
    48  
    49  	go grpcServer.Serve(socket)
    50  	defer grpcServer.Stop()
    51  
    52  	msptesttools.LoadMSPSetupForTesting()
    53  	identity, _ := mgmt.GetLocalSigningIdentityOrPanic().Serialize()
    54  
    55  	wg := sync.WaitGroup{}
    56  	wg.Add(10)
    57  	for i := 0; i < 10; i++ {
    58  		go func() {
    59  			defer wg.Done()
    60  			messageCryptoService := peergossip.NewMCS(&mocks.ChannelPolicyManagerGetter{}, localmsp.NewSigner(), mgmt.NewDeserializersManager())
    61  			secAdv := peergossip.NewSecurityAdvisor(mgmt.NewDeserializersManager())
    62  			err := InitGossipService(identity, "localhost:5611", grpcServer, messageCryptoService,
    63  				secAdv, nil)
    64  			assert.NoError(t, err)
    65  		}()
    66  	}
    67  	wg.Wait()
    68  
    69  	defer GetGossipService().Stop()
    70  	gossip := GetGossipService()
    71  
    72  	for i := 0; i < 10; i++ {
    73  		go func(gossipInstance GossipService) {
    74  			assert.Equal(t, gossip, GetGossipService())
    75  		}(gossip)
    76  	}
    77  
    78  	time.Sleep(time.Second * 2)
    79  }
    80  
    81  // Make sure *joinChannelMessage implements the api.JoinChannelMessage
    82  func TestJCMInterface(t *testing.T) {
    83  	_ = api.JoinChannelMessage(&joinChannelMessage{})
    84  }
    85  
    86  func TestLeaderElectionWithDeliverClient(t *testing.T) {
    87  
    88  	//Test check if leader election works with mock deliver service instance
    89  	//Configuration set to use dynamic leader election
    90  	//10 peers started, added to channel and at the end we check if only for one peer
    91  	//mockDeliverService.StartDeliverForChannel was invoked
    92  
    93  	viper.Set("peer.gossip.useLeaderElection", true)
    94  	viper.Set("peer.gossip.orgLeader", false)
    95  
    96  	n := 10
    97  	gossips := startPeers(t, n, 20000)
    98  
    99  	channelName := "chanA"
   100  	peerIndexes := make([]int, n)
   101  	for i := 0; i < n; i++ {
   102  		peerIndexes[i] = i
   103  	}
   104  	addPeersToChannel(t, n, 20000, channelName, gossips, peerIndexes)
   105  
   106  	waitForFullMembership(t, gossips, n, time.Second*20, time.Second*2)
   107  
   108  	services := make([]*electionService, n)
   109  
   110  	for i := 0; i < n; i++ {
   111  		deliverServiceFactory := &mockDeliverServiceFactory{
   112  			service: &mockDeliverService{
   113  				running: make(map[string]bool),
   114  			},
   115  		}
   116  		gossips[i].(*gossipServiceImpl).deliveryFactory = deliverServiceFactory
   117  		deliverServiceFactory.service.running[channelName] = false
   118  
   119  		gossips[i].InitializeChannel(channelName, &mockLedgerInfo{1}, []string{"localhost:5005"})
   120  		service, exist := gossips[i].(*gossipServiceImpl).leaderElection[channelName]
   121  		assert.True(t, exist, "Leader election service should be created for peer %d and channel %s", i, channelName)
   122  		services[i] = &electionService{nil, false, 0}
   123  		services[i].LeaderElectionService = service
   124  	}
   125  
   126  	// Is single leader was elected.
   127  	assert.True(t, waitForLeaderElection(t, services, time.Second*30, time.Second*2), "One leader should be selected")
   128  
   129  	startsNum := 0
   130  	for i := 0; i < n; i++ {
   131  		// Is mockDeliverService.StartDeliverForChannel in current peer for the specific channel was invoked
   132  		if gossips[i].(*gossipServiceImpl).deliveryService.(*mockDeliverService).running[channelName] {
   133  			startsNum++
   134  		}
   135  	}
   136  
   137  	assert.Equal(t, 1, startsNum, "Only for one peer delivery client should start")
   138  
   139  	stopPeers(gossips)
   140  }
   141  
   142  func TestWithStaticDeliverClientLeader(t *testing.T) {
   143  
   144  	//Tests check if static leader flag works ok.
   145  	//Leader election flag set to false, and static leader flag set to true
   146  	//Two gossip service instances (peers) created.
   147  	//Each peer is added to channel and should run mock delivery client
   148  	//After that each peer added to another client and it should run deliver client for this channel as well.
   149  
   150  	viper.Set("peer.gossip.useLeaderElection", false)
   151  	viper.Set("peer.gossip.orgLeader", true)
   152  
   153  	n := 2
   154  	gossips := startPeers(t, n, 20000)
   155  
   156  	channelName := "chanA"
   157  	peerIndexes := make([]int, n)
   158  	for i := 0; i < n; i++ {
   159  		peerIndexes[i] = i
   160  	}
   161  
   162  	addPeersToChannel(t, n, 20000, channelName, gossips, peerIndexes)
   163  
   164  	waitForFullMembership(t, gossips, n, time.Second*30, time.Second*2)
   165  
   166  	deliverServiceFactory := &mockDeliverServiceFactory{
   167  		service: &mockDeliverService{
   168  			running: make(map[string]bool),
   169  		},
   170  	}
   171  
   172  	for i := 0; i < n; i++ {
   173  		gossips[i].(*gossipServiceImpl).deliveryFactory = deliverServiceFactory
   174  		deliverServiceFactory.service.running[channelName] = false
   175  		gossips[i].InitializeChannel(channelName, &mockLedgerInfo{1}, []string{"localhost:5005"})
   176  	}
   177  
   178  	for i := 0; i < n; i++ {
   179  		assert.NotNil(t, gossips[i].(*gossipServiceImpl).deliveryService, "Delivery service not initiated in peer %d", i)
   180  		assert.True(t, gossips[i].(*gossipServiceImpl).deliveryService.(*mockDeliverService).running[channelName], "Block deliverer not started for peer %d", i)
   181  	}
   182  
   183  	channelName = "chanB"
   184  	for i := 0; i < n; i++ {
   185  		deliverServiceFactory.service.running[channelName] = false
   186  		gossips[i].InitializeChannel(channelName, &mockLedgerInfo{1}, []string{"localhost:5005"})
   187  	}
   188  
   189  	for i := 0; i < n; i++ {
   190  		assert.NotNil(t, gossips[i].(*gossipServiceImpl).deliveryService, "Delivery service not initiated in peer %d", i)
   191  		assert.True(t, gossips[i].(*gossipServiceImpl).deliveryService.(*mockDeliverService).running[channelName], "Block deliverer not started for peer %d", i)
   192  	}
   193  
   194  	stopPeers(gossips)
   195  }
   196  
   197  func TestWithStaticDeliverClientNotLeader(t *testing.T) {
   198  	viper.Set("peer.gossip.useLeaderElection", false)
   199  	viper.Set("peer.gossip.orgLeader", false)
   200  
   201  	n := 2
   202  	gossips := startPeers(t, n, 20000)
   203  
   204  	channelName := "chanA"
   205  	peerIndexes := make([]int, n)
   206  	for i := 0; i < n; i++ {
   207  		peerIndexes[i] = i
   208  	}
   209  
   210  	addPeersToChannel(t, n, 20000, channelName, gossips, peerIndexes)
   211  
   212  	waitForFullMembership(t, gossips, n, time.Second*30, time.Second*2)
   213  
   214  	deliverServiceFactory := &mockDeliverServiceFactory{
   215  		service: &mockDeliverService{
   216  			running: make(map[string]bool),
   217  		},
   218  	}
   219  
   220  	for i := 0; i < n; i++ {
   221  		gossips[i].(*gossipServiceImpl).deliveryFactory = deliverServiceFactory
   222  		deliverServiceFactory.service.running[channelName] = false
   223  		gossips[i].InitializeChannel(channelName, &mockLedgerInfo{1}, []string{"localhost:5005"})
   224  	}
   225  
   226  	for i := 0; i < n; i++ {
   227  		assert.NotNil(t, gossips[i].(*gossipServiceImpl).deliveryService, "Delivery service not initiated in peer %d", i)
   228  		assert.False(t, gossips[i].(*gossipServiceImpl).deliveryService.(*mockDeliverService).running[channelName], "Block deliverer should not be started for peer %d", i)
   229  	}
   230  
   231  	stopPeers(gossips)
   232  }
   233  
   234  func TestWithStaticDeliverClientBothStaticAndLeaderElection(t *testing.T) {
   235  	viper.Set("peer.gossip.useLeaderElection", true)
   236  	viper.Set("peer.gossip.orgLeader", true)
   237  
   238  	n := 2
   239  	gossips := startPeers(t, n, 20000)
   240  
   241  	channelName := "chanA"
   242  	peerIndexes := make([]int, n)
   243  	for i := 0; i < n; i++ {
   244  		peerIndexes[i] = i
   245  	}
   246  
   247  	addPeersToChannel(t, n, 20000, channelName, gossips, peerIndexes)
   248  
   249  	waitForFullMembership(t, gossips, n, time.Second*30, time.Second*2)
   250  
   251  	deliverServiceFactory := &mockDeliverServiceFactory{
   252  		service: &mockDeliverService{
   253  			running: make(map[string]bool),
   254  		},
   255  	}
   256  
   257  	for i := 0; i < n; i++ {
   258  		gossips[i].(*gossipServiceImpl).deliveryFactory = deliverServiceFactory
   259  		assert.Panics(t, func() {
   260  			gossips[i].InitializeChannel(channelName, &mockLedgerInfo{1}, []string{"localhost:5005"})
   261  		}, "Dynamic leader lection based and static connection to ordering service can't exist simultaniosly")
   262  	}
   263  
   264  	stopPeers(gossips)
   265  }
   266  
   267  type mockDeliverServiceFactory struct {
   268  	service *mockDeliverService
   269  }
   270  
   271  func (mf *mockDeliverServiceFactory) Service(g GossipService, endpoints []string, mcs api.MessageCryptoService) (deliverclient.DeliverService, error) {
   272  	return mf.service, nil
   273  }
   274  
   275  type mockDeliverService struct {
   276  	running map[string]bool
   277  }
   278  
   279  func (ds *mockDeliverService) StartDeliverForChannel(chainID string, ledgerInfo blocksprovider.LedgerInfo) error {
   280  	ds.running[chainID] = true
   281  	return nil
   282  }
   283  
   284  func (ds *mockDeliverService) StopDeliverForChannel(chainID string) error {
   285  	ds.running[chainID] = false
   286  	return nil
   287  }
   288  
   289  func (ds *mockDeliverService) Stop() {
   290  }
   291  
   292  type mockLedgerInfo struct {
   293  	Height uint64
   294  }
   295  
   296  // LedgerHeight returns mocked value to the ledger height
   297  func (li *mockLedgerInfo) LedgerHeight() (uint64, error) {
   298  	return li.Height, nil
   299  }
   300  
   301  // Commit block to the ledger
   302  func (li *mockLedgerInfo) Commit(block *common.Block) error {
   303  	return nil
   304  }
   305  
   306  // Gets blocks with sequence numbers provided in the slice
   307  func (li *mockLedgerInfo) GetBlocks(blockSeqs []uint64) []*common.Block {
   308  	return make([]*common.Block, 0)
   309  }
   310  
   311  // Closes committing service
   312  func (li *mockLedgerInfo) Close() {
   313  }
   314  
   315  func TestLeaderElectionWithRealGossip(t *testing.T) {
   316  
   317  	// Spawn 10 gossip instances with single channel and inside same organization
   318  	// Run leader election on top of each gossip instance and check that only one leader chosen
   319  	// Create another channel includes sub-set of peers over same gossip instances {1,3,5,7}
   320  	// Run additional leader election services for new channel
   321  	// Check correct leader still exist for first channel and new correct leader chosen in second channel
   322  	// Stop gossip instances of leader peers for both channels and see that new leader chosen for both
   323  
   324  	// Creating gossip service instances for peers
   325  	n := 10
   326  	gossips := startPeers(t, n, 20000)
   327  
   328  	// Joining all peers to first channel
   329  	channelName := "chanA"
   330  	peerIndexes := make([]int, n)
   331  	for i := 0; i < n; i++ {
   332  		peerIndexes[i] = i
   333  	}
   334  	addPeersToChannel(t, n, 20000, channelName, gossips, peerIndexes)
   335  
   336  	waitForFullMembership(t, gossips, n, time.Second*30, time.Second*2)
   337  
   338  	logger.Warning("Starting leader election services")
   339  
   340  	//Starting leader election services
   341  	services := make([]*electionService, n)
   342  
   343  	for i := 0; i < n; i++ {
   344  		services[i] = &electionService{nil, false, 0}
   345  		services[i].LeaderElectionService = gossips[i].(*gossipServiceImpl).newLeaderElectionComponent(channelName, services[i].callback)
   346  	}
   347  
   348  	logger.Warning("Waiting for leader election")
   349  
   350  	assert.True(t, waitForLeaderElection(t, services, time.Second*30, time.Second*2), "One leader should be selected")
   351  
   352  	startsNum := 0
   353  	for i := 0; i < n; i++ {
   354  		// Is callback function was invoked by this leader election service instance
   355  		if services[i].callbackInvokeRes {
   356  			startsNum++
   357  		}
   358  	}
   359  	//Only leader should invoke callback function, so it is double check that only one leader exists
   360  	assert.Equal(t, 1, startsNum, "Only for one peer callback function should be called - chanA")
   361  
   362  	// Adding some peers to new channel and creating leader election services for peers in new channel
   363  	// Expecting peer 1 (first in list of election services) to become leader of second channel
   364  	secondChannelPeerIndexes := []int{1, 3, 5, 7}
   365  	secondChannelName := "chanB"
   366  	secondChannelServices := make([]*electionService, len(secondChannelPeerIndexes))
   367  	addPeersToChannel(t, n, 20000, secondChannelName, gossips, secondChannelPeerIndexes)
   368  
   369  	for idx, i := range secondChannelPeerIndexes {
   370  		secondChannelServices[idx] = &electionService{nil, false, 0}
   371  		secondChannelServices[idx].LeaderElectionService = gossips[i].(*gossipServiceImpl).newLeaderElectionComponent(secondChannelName, secondChannelServices[idx].callback)
   372  	}
   373  
   374  	assert.True(t, waitForLeaderElection(t, secondChannelServices, time.Second*30, time.Second*2), "One leader should be selected for chanB")
   375  	assert.True(t, waitForLeaderElection(t, services, time.Second*30, time.Second*2), "One leader should be selected for chanA")
   376  
   377  	startsNum = 0
   378  	for i := 0; i < n; i++ {
   379  		if services[i].callbackInvokeRes {
   380  			startsNum++
   381  		}
   382  	}
   383  	assert.Equal(t, 1, startsNum, "Only for one peer callback function should be called - chanA")
   384  
   385  	startsNum = 0
   386  	for i := 0; i < len(secondChannelServices); i++ {
   387  		if secondChannelServices[i].callbackInvokeRes {
   388  			startsNum++
   389  		}
   390  	}
   391  	assert.Equal(t, 1, startsNum, "Only for one peer callback function should be called - chanB")
   392  
   393  	//Stopping 2 gossip instances(peer 0 and peer 1), should init re-election
   394  	//Now peer 2 become leader for first channel and peer 3 for second channel
   395  
   396  	logger.Warning("Killing 2 peers, initiation new leader election")
   397  
   398  	stopPeers(gossips[:2])
   399  
   400  	waitForFullMembership(t, gossips[2:], n-2, time.Second*30, time.Second*2)
   401  
   402  	assert.True(t, waitForLeaderElection(t, services[2:], time.Second*30, time.Second*2), "One leader should be selected after re-election - chanA")
   403  	assert.True(t, waitForLeaderElection(t, secondChannelServices[1:], time.Second*30, time.Second*2), "One leader should be selected after re-election - chanB")
   404  
   405  	startsNum = 0
   406  	for i := 2; i < n; i++ {
   407  		if services[i].callbackInvokeRes {
   408  			startsNum++
   409  		}
   410  	}
   411  	assert.Equal(t, 1, startsNum, "Only for one peer callback function should be called after re-election - chanA")
   412  
   413  	startsNum = 0
   414  	for i := 1; i < len(secondChannelServices); i++ {
   415  		if secondChannelServices[i].callbackInvokeRes {
   416  			startsNum++
   417  		}
   418  	}
   419  	assert.Equal(t, 1, startsNum, "Only for one peer callback function should be called after re-election - chanB")
   420  
   421  	stopServices(secondChannelServices)
   422  	stopServices(services)
   423  	stopPeers(gossips[2:])
   424  }
   425  
   426  type electionService struct {
   427  	election.LeaderElectionService
   428  	callbackInvokeRes   bool
   429  	callbackInvokeCount int
   430  }
   431  
   432  func (es *electionService) callback(isLeader bool) {
   433  	es.callbackInvokeRes = isLeader
   434  	es.callbackInvokeCount = es.callbackInvokeCount + 1
   435  }
   436  
   437  type joinChanMsg struct {
   438  }
   439  
   440  // SequenceNumber returns the sequence number of the block this joinChanMsg
   441  // is derived from
   442  func (jmc *joinChanMsg) SequenceNumber() uint64 {
   443  	return uint64(time.Now().UnixNano())
   444  }
   445  
   446  // Members returns the organizations of the channel
   447  func (jmc *joinChanMsg) Members() []api.OrgIdentityType {
   448  	return []api.OrgIdentityType{orgInChannelA}
   449  }
   450  
   451  // AnchorPeersOf returns the anchor peers of the given organization
   452  func (jmc *joinChanMsg) AnchorPeersOf(org api.OrgIdentityType) []api.AnchorPeer {
   453  	return []api.AnchorPeer{}
   454  }
   455  
   456  func waitForFullMembership(t *testing.T, gossips []GossipService, peersNum int, timeout time.Duration, testPollInterval time.Duration) bool {
   457  	end := time.Now().Add(timeout)
   458  	var correctPeers int
   459  	for time.Now().Before(end) {
   460  		correctPeers = 0
   461  		for _, g := range gossips {
   462  			if len(g.Peers()) == (peersNum - 1) {
   463  				correctPeers++
   464  			}
   465  		}
   466  		if correctPeers == peersNum {
   467  			return true
   468  		}
   469  		time.Sleep(testPollInterval)
   470  	}
   471  	logger.Warningf("Only %d peers have full membership", correctPeers)
   472  	return false
   473  }
   474  
   475  func waitForMultipleLeadersElection(t *testing.T, services []*electionService, leadersNum int, timeout time.Duration, testPollInterval time.Duration) bool {
   476  	logger.Warning("Waiting for", leadersNum, "leaders")
   477  	end := time.Now().Add(timeout)
   478  	correctNumberOfLeadersFound := false
   479  	leaders := 0
   480  	for time.Now().Before(end) {
   481  		leaders = 0
   482  		for _, s := range services {
   483  			if s.IsLeader() {
   484  				leaders++
   485  			}
   486  		}
   487  		if leaders == leadersNum {
   488  			if correctNumberOfLeadersFound {
   489  				return true
   490  			}
   491  			correctNumberOfLeadersFound = true
   492  		} else {
   493  			correctNumberOfLeadersFound = false
   494  		}
   495  		time.Sleep(testPollInterval)
   496  	}
   497  	logger.Warning("Incorrect number of leaders", leaders)
   498  	for i, s := range services {
   499  		logger.Warning("Peer at index", i, "is leader", s.IsLeader())
   500  	}
   501  	return false
   502  }
   503  
   504  func waitForLeaderElection(t *testing.T, services []*electionService, timeout time.Duration, testPollInterval time.Duration) bool {
   505  	return waitForMultipleLeadersElection(t, services, 1, timeout, testPollInterval)
   506  }
   507  
   508  func waitUntilOrFailBlocking(t *testing.T, f func(), timeout time.Duration) {
   509  	successChan := make(chan struct{}, 1)
   510  	go func() {
   511  		f()
   512  		successChan <- struct{}{}
   513  	}()
   514  	select {
   515  	case <-time.NewTimer(timeout).C:
   516  		break
   517  	case <-successChan:
   518  		return
   519  	}
   520  	util.PrintStackTrace()
   521  	assert.Fail(t, "Timeout expired!")
   522  }
   523  
   524  func stopServices(services []*electionService) {
   525  	stoppingWg := sync.WaitGroup{}
   526  	stoppingWg.Add(len(services))
   527  	for i, sI := range services {
   528  		go func(i int, s_i election.LeaderElectionService) {
   529  			defer stoppingWg.Done()
   530  			s_i.Stop()
   531  		}(i, sI)
   532  	}
   533  	stoppingWg.Wait()
   534  	time.Sleep(time.Second * time.Duration(2))
   535  }
   536  
   537  func stopPeers(peers []GossipService) {
   538  	stoppingWg := sync.WaitGroup{}
   539  	stoppingWg.Add(len(peers))
   540  	for i, pI := range peers {
   541  		go func(i int, p_i GossipService) {
   542  			defer stoppingWg.Done()
   543  			p_i.Stop()
   544  		}(i, pI)
   545  	}
   546  	stoppingWg.Wait()
   547  	time.Sleep(time.Second * time.Duration(2))
   548  }
   549  
   550  func addPeersToChannel(t *testing.T, n int, portPrefix int, channel string, peers []GossipService, peerIndexes []int) {
   551  	jcm := &joinChanMsg{}
   552  
   553  	wg := sync.WaitGroup{}
   554  	for _, i := range peerIndexes {
   555  		wg.Add(1)
   556  		go func(i int) {
   557  			peers[i].JoinChan(jcm, gossipCommon.ChainID(channel))
   558  			peers[i].UpdateChannelMetadata([]byte("bla bla"), gossipCommon.ChainID(channel))
   559  			wg.Done()
   560  		}(i)
   561  	}
   562  	waitUntilOrFailBlocking(t, wg.Wait, time.Second*10)
   563  }
   564  
   565  func startPeers(t *testing.T, n int, portPrefix int) []GossipService {
   566  
   567  	peers := make([]GossipService, n)
   568  	wg := sync.WaitGroup{}
   569  	for i := 0; i < n; i++ {
   570  		wg.Add(1)
   571  		go func(i int) {
   572  
   573  			peers[i] = newGossipInstance(portPrefix, i, 100, 0, 1, 2, 3, 4, 5)
   574  			wg.Done()
   575  		}(i)
   576  	}
   577  	waitUntilOrFailBlocking(t, wg.Wait, time.Second*10)
   578  
   579  	return peers
   580  }
   581  
   582  func newGossipInstance(portPrefix int, id int, maxMsgCount int, boot ...int) GossipService {
   583  	port := id + portPrefix
   584  	conf := &gossip.Config{
   585  		BindPort:                   port,
   586  		BootstrapPeers:             bootPeers(portPrefix, boot...),
   587  		ID:                         fmt.Sprintf("p%d", id),
   588  		MaxBlockCountToStore:       maxMsgCount,
   589  		MaxPropagationBurstLatency: time.Duration(500) * time.Millisecond,
   590  		MaxPropagationBurstSize:    20,
   591  		PropagateIterations:        1,
   592  		PropagatePeerNum:           3,
   593  		PullInterval:               time.Duration(2) * time.Second,
   594  		PullPeerNum:                5,
   595  		InternalEndpoint:           fmt.Sprintf("localhost:%d", port),
   596  		ExternalEndpoint:           fmt.Sprintf("1.2.3.4:%d", port),
   597  		PublishCertPeriod:          time.Duration(4) * time.Second,
   598  		PublishStateInfoInterval:   time.Duration(1) * time.Second,
   599  		RequestStateInfoInterval:   time.Duration(1) * time.Second,
   600  	}
   601  	selfId := api.PeerIdentityType(conf.InternalEndpoint)
   602  	cryptoService := &naiveCryptoService{}
   603  	idMapper := identity.NewIdentityMapper(cryptoService, selfId)
   604  
   605  	gossip := gossip.NewGossipServiceWithServer(conf, &orgCryptoService{}, cryptoService,
   606  		idMapper, selfId, nil)
   607  
   608  	gossipService := &gossipServiceImpl{
   609  		gossipSvc:       gossip,
   610  		chains:          make(map[string]state.GossipStateProvider),
   611  		leaderElection:  make(map[string]election.LeaderElectionService),
   612  		deliveryFactory: &deliveryFactoryImpl{},
   613  		idMapper:        idMapper,
   614  		peerIdentity:    api.PeerIdentityType(conf.InternalEndpoint),
   615  	}
   616  
   617  	return gossipService
   618  }
   619  
   620  func bootPeers(portPrefix int, ids ...int) []string {
   621  	peers := []string{}
   622  	for _, id := range ids {
   623  		peers = append(peers, fmt.Sprintf("localhost:%d", id+portPrefix))
   624  	}
   625  	return peers
   626  }
   627  
   628  type naiveCryptoService struct {
   629  }
   630  
   631  type orgCryptoService struct {
   632  }
   633  
   634  // OrgByPeerIdentity returns the OrgIdentityType
   635  // of a given peer identity
   636  func (*orgCryptoService) OrgByPeerIdentity(identity api.PeerIdentityType) api.OrgIdentityType {
   637  	return orgInChannelA
   638  }
   639  
   640  // Verify verifies a JoinChanMessage, returns nil on success,
   641  // and an error on failure
   642  func (*orgCryptoService) Verify(joinChanMsg api.JoinChannelMessage) error {
   643  	return nil
   644  }
   645  
   646  // VerifyByChannel verifies a peer's signature on a message in the context
   647  // of a specific channel
   648  func (*naiveCryptoService) VerifyByChannel(_ gossipCommon.ChainID, _ api.PeerIdentityType, _, _ []byte) error {
   649  	return nil
   650  }
   651  
   652  func (*naiveCryptoService) ValidateIdentity(peerIdentity api.PeerIdentityType) error {
   653  	return nil
   654  }
   655  
   656  // GetPKIidOfCert returns the PKI-ID of a peer's identity
   657  func (*naiveCryptoService) GetPKIidOfCert(peerIdentity api.PeerIdentityType) gossipCommon.PKIidType {
   658  	return gossipCommon.PKIidType(peerIdentity)
   659  }
   660  
   661  // VerifyBlock returns nil if the block is properly signed,
   662  // else returns error
   663  func (*naiveCryptoService) VerifyBlock(chainID gossipCommon.ChainID, seqNum uint64, signedBlock []byte) error {
   664  	return nil
   665  }
   666  
   667  // Sign signs msg with this peer's signing key and outputs
   668  // the signature if no error occurred.
   669  func (*naiveCryptoService) Sign(msg []byte) ([]byte, error) {
   670  	return msg, nil
   671  }
   672  
   673  // Verify checks that signature is a valid signature of message under a peer's verification key.
   674  // If the verification succeeded, Verify returns nil meaning no error occurred.
   675  // If peerCert is nil, then the signature is verified against this peer's verification key.
   676  func (*naiveCryptoService) Verify(peerIdentity api.PeerIdentityType, signature, message []byte) error {
   677  	equal := bytes.Equal(signature, message)
   678  	if !equal {
   679  		return fmt.Errorf("Wrong signature:%v, %v", signature, message)
   680  	}
   681  	return nil
   682  }
   683  
   684  var orgInChannelA = api.OrgIdentityType("ORG1")
   685  
   686  func TestInvalidInitialization(t *testing.T) {
   687  	// Test whenever gossip service is indeed singleton
   688  	grpcServer := grpc.NewServer()
   689  	socket, error := net.Listen("tcp", fmt.Sprintf("%s:%d", "", 7611))
   690  	assert.NoError(t, error)
   691  
   692  	go grpcServer.Serve(socket)
   693  	defer grpcServer.Stop()
   694  
   695  	secAdv := peergossip.NewSecurityAdvisor(mgmt.NewDeserializersManager())
   696  	err := InitGossipService(api.PeerIdentityType("IDENTITY"), "localhost:7611", grpcServer,
   697  		&naiveCryptoService{}, secAdv, nil)
   698  	assert.NoError(t, err)
   699  	gService := GetGossipService().(*gossipServiceImpl)
   700  	defer gService.Stop()
   701  
   702  	dc, err := gService.deliveryFactory.Service(gService, []string{}, &naiveCryptoService{})
   703  	assert.Nil(t, dc)
   704  	assert.Error(t, err)
   705  
   706  	dc, err = gService.deliveryFactory.Service(gService, []string{"localhost:1984"}, &naiveCryptoService{})
   707  	assert.NotNil(t, dc)
   708  	assert.NoError(t, err)
   709  }
   710  
   711  func TestChannelConfig(t *testing.T) {
   712  	// Test whenever gossip service is indeed singleton
   713  	grpcServer := grpc.NewServer()
   714  	socket, error := net.Listen("tcp", fmt.Sprintf("%s:%d", "", 6611))
   715  	assert.NoError(t, error)
   716  
   717  	go grpcServer.Serve(socket)
   718  	defer grpcServer.Stop()
   719  
   720  	secAdv := peergossip.NewSecurityAdvisor(mgmt.NewDeserializersManager())
   721  	error = InitGossipService(api.PeerIdentityType("IDENTITY"), "localhost:6611", grpcServer,
   722  		&naiveCryptoService{}, secAdv, nil)
   723  	assert.NoError(t, error)
   724  	gService := GetGossipService().(*gossipServiceImpl)
   725  	defer gService.Stop()
   726  
   727  	jcm := &joinChannelMessage{seqNum: 1, members2AnchorPeers: map[string][]api.AnchorPeer{
   728  		"A": {{Host: "host", Port: 5000}},
   729  	}}
   730  
   731  	assert.Equal(t, uint64(1), jcm.SequenceNumber())
   732  
   733  	mc := &mockConfig{
   734  		sequence: 1,
   735  		orgs: map[string]config.ApplicationOrg{
   736  			string(orgInChannelA): &appGrp{
   737  				mspID:       string(orgInChannelA),
   738  				anchorPeers: []*peer.AnchorPeer{},
   739  			},
   740  		},
   741  	}
   742  	gService.JoinChan(jcm, gossipCommon.ChainID("A"))
   743  	gService.configUpdated(mc)
   744  	assert.True(t, gService.amIinChannel(string(orgInChannelA), mc))
   745  }