github.com/Hnampk/my-fabric@v0.0.0-20201028083322-75069da399c0/gossip/gossip/gossip_impl.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package gossip
     8  
     9  import (
    10  	"bytes"
    11  	"fmt"
    12  	"net"
    13  	"reflect"
    14  	"sync"
    15  	"sync/atomic"
    16  	"time"
    17  
    18  	"github.com/golang/protobuf/proto"
    19  	pg "github.com/hyperledger/fabric-protos-go/gossip"
    20  	"github.com/hyperledger/fabric/gossip/api"
    21  	"github.com/hyperledger/fabric/gossip/comm"
    22  	"github.com/hyperledger/fabric/gossip/common"
    23  	"github.com/hyperledger/fabric/gossip/discovery"
    24  	"github.com/hyperledger/fabric/gossip/filter"
    25  	"github.com/hyperledger/fabric/gossip/gossip/algo"
    26  	"github.com/hyperledger/fabric/gossip/gossip/channel"
    27  	"github.com/hyperledger/fabric/gossip/gossip/msgstore"
    28  	"github.com/hyperledger/fabric/gossip/gossip/pull"
    29  	"github.com/hyperledger/fabric/gossip/identity"
    30  	"github.com/hyperledger/fabric/gossip/metrics"
    31  	"github.com/hyperledger/fabric/gossip/protoext"
    32  	"github.com/hyperledger/fabric/gossip/util"
    33  	"github.com/pkg/errors"
    34  	"google.golang.org/grpc"
    35  )
    36  
    37  const (
    38  	presumedDeadChanSize = 100
    39  	acceptChanSize       = 100
    40  )
    41  
    42  type channelRoutingFilterFactory func(channel.GossipChannel) filter.RoutingFilter
    43  
    44  // Node is a member of a gossip network
    45  type Node struct {
    46  	selfIdentity          api.PeerIdentityType
    47  	includeIdentityPeriod time.Time
    48  	certStore             *certStore
    49  	idMapper              identity.Mapper
    50  	presumedDead          chan common.PKIidType
    51  	disc                  discovery.Discovery
    52  	comm                  comm.Comm
    53  	selfOrg               api.OrgIdentityType
    54  	*comm.ChannelDeMultiplexer
    55  	logger            util.Logger
    56  	stopSignal        *sync.WaitGroup
    57  	conf              *Config
    58  	toDieChan         chan struct{}
    59  	stopFlag          int32
    60  	emitter           batchingEmitter
    61  	discAdapter       *discoveryAdapter
    62  	secAdvisor        api.SecurityAdvisor
    63  	chanState         *channelState
    64  	disSecAdap        *discoverySecurityAdapter
    65  	mcs               api.MessageCryptoService
    66  	stateInfoMsgStore msgstore.MessageStore
    67  	certPuller        pull.Mediator
    68  	gossipMetrics     *metrics.GossipMetrics
    69  }
    70  
    71  // New creates a gossip instance attached to a gRPC server
    72  func New(conf *Config, s *grpc.Server, sa api.SecurityAdvisor,
    73  	mcs api.MessageCryptoService, selfIdentity api.PeerIdentityType,
    74  	secureDialOpts api.PeerSecureDialOpts, gossipMetrics *metrics.GossipMetrics) *Node {
    75  	var err error
    76  
    77  	lgr := util.GetLogger(util.GossipLogger, conf.ID)
    78  
    79  	g := &Node{
    80  		selfOrg:               sa.OrgByPeerIdentity(selfIdentity),
    81  		secAdvisor:            sa,
    82  		selfIdentity:          selfIdentity,
    83  		presumedDead:          make(chan common.PKIidType, presumedDeadChanSize),
    84  		disc:                  nil,
    85  		mcs:                   mcs,
    86  		conf:                  conf,
    87  		ChannelDeMultiplexer:  comm.NewChannelDemultiplexer(),
    88  		logger:                lgr,
    89  		toDieChan:             make(chan struct{}),
    90  		stopFlag:              int32(0),
    91  		stopSignal:            &sync.WaitGroup{},
    92  		includeIdentityPeriod: time.Now().Add(conf.PublishCertPeriod),
    93  		gossipMetrics:         gossipMetrics,
    94  	}
    95  	g.stateInfoMsgStore = g.newStateInfoMsgStore()
    96  
    97  	g.idMapper = identity.NewIdentityMapper(mcs, selfIdentity, func(pkiID common.PKIidType, identity api.PeerIdentityType) {
    98  		g.comm.CloseConn(&comm.RemotePeer{PKIID: pkiID})
    99  		g.certPuller.Remove(string(pkiID))
   100  	}, sa)
   101  
   102  	commConfig := comm.CommConfig{
   103  		DialTimeout:  conf.DialTimeout,
   104  		ConnTimeout:  conf.ConnTimeout,
   105  		RecvBuffSize: conf.RecvBuffSize,
   106  		SendBuffSize: conf.SendBuffSize,
   107  	}
   108  	g.comm, err = comm.NewCommInstance(s, conf.TLSCerts, g.idMapper, selfIdentity, secureDialOpts, sa,
   109  		gossipMetrics.CommMetrics, commConfig)
   110  
   111  	if err != nil {
   112  		lgr.Error("Failed instntiating communication layer:", err)
   113  		return nil
   114  	}
   115  
   116  	g.chanState = newChannelState(g)
   117  	g.emitter = newBatchingEmitter(conf.PropagateIterations,
   118  		conf.MaxPropagationBurstSize, conf.MaxPropagationBurstLatency,
   119  		g.sendGossipBatch)
   120  
   121  	g.discAdapter = g.newDiscoveryAdapter()
   122  	g.disSecAdap = g.newDiscoverySecurityAdapter()
   123  
   124  	discoveryConfig := discovery.DiscoveryConfig{
   125  		AliveTimeInterval:            conf.AliveTimeInterval,
   126  		AliveExpirationTimeout:       conf.AliveExpirationTimeout,
   127  		AliveExpirationCheckInterval: conf.AliveExpirationCheckInterval,
   128  		ReconnectInterval:            conf.ReconnectInterval,
   129  		BootstrapPeers:               conf.BootstrapPeers,
   130  	}
   131  	g.disc = discovery.NewDiscoveryService(g.selfNetworkMember(), g.discAdapter, g.disSecAdap, g.disclosurePolicy,
   132  		discoveryConfig)
   133  	g.logger.Infof("Creating gossip service with self membership of %s", g.selfNetworkMember())
   134  
   135  	g.certPuller = g.createCertStorePuller()
   136  	g.certStore = newCertStore(g.certPuller, g.idMapper, selfIdentity, mcs)
   137  
   138  	if g.conf.ExternalEndpoint == "" {
   139  		g.logger.Warning("External endpoint is empty, peer will not be accessible outside of its organization")
   140  	}
   141  	// Adding delta for handlePresumedDead and
   142  	// acceptMessages goRoutines to block on Wait
   143  	g.stopSignal.Add(2)
   144  	go g.start()
   145  	go g.connect2BootstrapPeers()
   146  
   147  	return g
   148  }
   149  
   150  func (g *Node) newStateInfoMsgStore() msgstore.MessageStore {
   151  	pol := protoext.NewGossipMessageComparator(0)
   152  	return msgstore.NewMessageStoreExpirable(pol,
   153  		msgstore.Noop,
   154  		g.conf.PublishStateInfoInterval*100,
   155  		nil,
   156  		nil,
   157  		msgstore.Noop)
   158  }
   159  
   160  func (g *Node) selfNetworkMember() discovery.NetworkMember {
   161  	self := discovery.NetworkMember{
   162  		Endpoint:         g.conf.ExternalEndpoint,
   163  		PKIid:            g.comm.GetPKIid(),
   164  		Metadata:         []byte{},
   165  		InternalEndpoint: g.conf.InternalEndpoint,
   166  	}
   167  	if g.disc != nil {
   168  		self.Metadata = g.disc.Self().Metadata
   169  	}
   170  	return self
   171  }
   172  
   173  func newChannelState(g *Node) *channelState {
   174  	return &channelState{
   175  		stopping: int32(0),
   176  		channels: make(map[string]channel.GossipChannel),
   177  		g:        g,
   178  	}
   179  }
   180  
   181  func (g *Node) toDie() bool {
   182  	return atomic.LoadInt32(&g.stopFlag) == int32(1)
   183  }
   184  
   185  // JoinChan makes gossip participate in the given channel, or update it.
   186  func (g *Node) JoinChan(joinMsg api.JoinChannelMessage, channelID common.ChannelID) {
   187  	// joinMsg is supposed to have been already verified
   188  	g.chanState.joinChannel(joinMsg, channelID, g.gossipMetrics.MembershipMetrics)
   189  
   190  	g.logger.Info("Joining gossip network of channel", string(channelID), "with", len(joinMsg.Members()), "organizations")
   191  	for _, org := range joinMsg.Members() {
   192  		g.learnAnchorPeers(string(channelID), org, joinMsg.AnchorPeersOf(org))
   193  	}
   194  }
   195  
   196  // LeaveChan makes gossip stop participating in the given channel
   197  func (g *Node) LeaveChan(channelID common.ChannelID) {
   198  	gc := g.chanState.getGossipChannelByChainID(channelID)
   199  	if gc == nil {
   200  		g.logger.Debug("No such channel", channelID)
   201  		return
   202  	}
   203  	gc.LeaveChannel()
   204  }
   205  
   206  // SuspectPeers makes the gossip instance validate identities of suspected peers, and close
   207  // any connections to peers with identities that are found invalid
   208  func (g *Node) SuspectPeers(isSuspected api.PeerSuspector) {
   209  	g.certStore.suspectPeers(isSuspected)
   210  }
   211  
   212  func (g *Node) learnAnchorPeers(channel string, orgOfAnchorPeers api.OrgIdentityType, anchorPeers []api.AnchorPeer) {
   213  	if len(anchorPeers) == 0 {
   214  		g.logger.Info("No configured anchor peers of", string(orgOfAnchorPeers), "for channel", channel, "to learn about")
   215  		return
   216  	}
   217  	g.logger.Info("Learning about the configured anchor peers of", string(orgOfAnchorPeers), "for channel", channel, ":", anchorPeers)
   218  	for _, ap := range anchorPeers {
   219  		if ap.Host == "" {
   220  			g.logger.Warning("Got empty hostname, skipping connecting to anchor peer", ap)
   221  			continue
   222  		}
   223  		if ap.Port == 0 {
   224  			g.logger.Warning("Got invalid port (0), skipping connecting to anchor peer", ap)
   225  			continue
   226  		}
   227  		endpoint := net.JoinHostPort(ap.Host, fmt.Sprintf("%d", ap.Port))
   228  		// Skip connecting to self
   229  		if g.selfNetworkMember().Endpoint == endpoint || g.selfNetworkMember().InternalEndpoint == endpoint {
   230  			g.logger.Info("Anchor peer with same endpoint, skipping connecting to myself")
   231  			continue
   232  		}
   233  
   234  		inOurOrg := bytes.Equal(g.selfOrg, orgOfAnchorPeers)
   235  		if !inOurOrg && g.selfNetworkMember().Endpoint == "" {
   236  			g.logger.Infof("Anchor peer %s:%d isn't in our org(%v) and we have no external endpoint, skipping", ap.Host, ap.Port, string(orgOfAnchorPeers))
   237  			continue
   238  		}
   239  		identifier := func() (*discovery.PeerIdentification, error) {
   240  			remotePeerIdentity, err := g.comm.Handshake(&comm.RemotePeer{Endpoint: endpoint})
   241  			if err != nil {
   242  				g.logger.Warningf("Deep probe of %s failed: %s", endpoint, err)
   243  				return nil, err
   244  			}
   245  			isAnchorPeerInMyOrg := bytes.Equal(g.selfOrg, g.secAdvisor.OrgByPeerIdentity(remotePeerIdentity))
   246  			if bytes.Equal(orgOfAnchorPeers, g.selfOrg) && !isAnchorPeerInMyOrg {
   247  				err := errors.Errorf("Anchor peer %s isn't in our org, but is claimed to be", endpoint)
   248  				g.logger.Warningf("%s", err)
   249  				return nil, err
   250  			}
   251  			pkiID := g.mcs.GetPKIidOfCert(remotePeerIdentity)
   252  			if len(pkiID) == 0 {
   253  				return nil, errors.Errorf("Wasn't able to extract PKI-ID of remote peer with identity of %v", remotePeerIdentity)
   254  			}
   255  			return &discovery.PeerIdentification{
   256  				ID:      pkiID,
   257  				SelfOrg: isAnchorPeerInMyOrg,
   258  			}, nil
   259  		}
   260  
   261  		g.disc.Connect(discovery.NetworkMember{
   262  			InternalEndpoint: endpoint, Endpoint: endpoint}, identifier)
   263  	}
   264  }
   265  
   266  func (g *Node) handlePresumedDead() {
   267  	defer g.logger.Debug("Exiting")
   268  	defer g.stopSignal.Done()
   269  	for {
   270  		select {
   271  		case <-g.toDieChan:
   272  			return
   273  		case deadEndpoint := <-g.comm.PresumedDead():
   274  			g.presumedDead <- deadEndpoint
   275  		}
   276  	}
   277  }
   278  
   279  func (g *Node) syncDiscovery() {
   280  	g.logger.Debug("Entering discovery sync with interval", g.conf.PullInterval)
   281  	defer g.logger.Debug("Exiting discovery sync loop")
   282  	for !g.toDie() {
   283  		g.disc.InitiateSync(g.conf.PullPeerNum)
   284  		time.Sleep(g.conf.PullInterval)
   285  	}
   286  }
   287  
   288  func (g *Node) start() {
   289  	go g.syncDiscovery()
   290  	go g.handlePresumedDead()
   291  
   292  	msgSelector := func(msg interface{}) bool {
   293  		gMsg, isGossipMsg := msg.(protoext.ReceivedMessage)
   294  		if !isGossipMsg {
   295  			return false
   296  		}
   297  
   298  		isConn := gMsg.GetGossipMessage().GetConn() != nil
   299  		isEmpty := gMsg.GetGossipMessage().GetEmpty() != nil
   300  		isPrivateData := protoext.IsPrivateDataMsg(gMsg.GetGossipMessage().GossipMessage)
   301  
   302  		return !(isConn || isEmpty || isPrivateData)
   303  	}
   304  
   305  	incMsgs := g.comm.Accept(msgSelector)
   306  
   307  	go g.acceptMessages(incMsgs)
   308  
   309  	g.logger.Info("Gossip instance", g.conf.ID, "started")
   310  }
   311  
   312  func (g *Node) acceptMessages(incMsgs <-chan protoext.ReceivedMessage) {
   313  	defer g.logger.Debug("Exiting")
   314  	defer g.stopSignal.Done()
   315  	for {
   316  		select {
   317  		case <-g.toDieChan:
   318  			return
   319  		case msg := <-incMsgs:
   320  			g.handleMessage(msg)
   321  		}
   322  	}
   323  }
   324  
   325  func (g *Node) handleMessage(m protoext.ReceivedMessage) {
   326  	if g.toDie() {
   327  		return
   328  	}
   329  
   330  	if m == nil || m.GetGossipMessage() == nil {
   331  		return
   332  	}
   333  
   334  	msg := m.GetGossipMessage()
   335  
   336  	g.logger.Debug("Entering,", m.GetConnectionInfo(), "sent us", msg)
   337  	defer g.logger.Debug("Exiting")
   338  
   339  	if !g.validateMsg(m) {
   340  		g.logger.Warning("Message", msg, "isn't valid")
   341  		return
   342  	}
   343  
   344  	if protoext.IsChannelRestricted(msg.GossipMessage) {
   345  		if gc := g.chanState.lookupChannelForMsg(m); gc == nil {
   346  			// If we're not in the channel, we should still forward to peers of our org
   347  			// in case it's a StateInfo message
   348  			if g.IsInMyOrg(discovery.NetworkMember{PKIid: m.GetConnectionInfo().ID}) && protoext.IsStateInfoMsg(msg.GossipMessage) {
   349  				if g.stateInfoMsgStore.Add(msg) {
   350  					g.emitter.Add(&emittedGossipMessage{
   351  						SignedGossipMessage: msg,
   352  						filter:              m.GetConnectionInfo().ID.IsNotSameFilter,
   353  					})
   354  				}
   355  			}
   356  			if !g.toDie() {
   357  				g.logger.Debug("No such channel", msg.Channel, "discarding message", msg)
   358  			}
   359  		} else {
   360  			if protoext.IsLeadershipMsg(m.GetGossipMessage().GossipMessage) {
   361  				if err := g.validateLeadershipMessage(m.GetGossipMessage()); err != nil {
   362  					g.logger.Warningf("Failed validating LeaderElection message: %+v", errors.WithStack(err))
   363  					return
   364  				}
   365  			}
   366  			gc.HandleMessage(m)
   367  		}
   368  		return
   369  	}
   370  
   371  	if selectOnlyDiscoveryMessages(m) {
   372  		// It's a membership request, check its self information
   373  		// matches the sender
   374  		if m.GetGossipMessage().GetMemReq() != nil {
   375  			sMsg, err := protoext.EnvelopeToGossipMessage(m.GetGossipMessage().GetMemReq().SelfInformation)
   376  			if err != nil {
   377  				g.logger.Warningf("Got membership request with invalid selfInfo: %+v", errors.WithStack(err))
   378  				return
   379  			}
   380  			if !protoext.IsAliveMsg(sMsg.GossipMessage) {
   381  				g.logger.Warning("Got membership request with selfInfo that isn't an AliveMessage")
   382  				return
   383  			}
   384  			if !bytes.Equal(sMsg.GetAliveMsg().Membership.PkiId, m.GetConnectionInfo().ID) {
   385  				g.logger.Warning("Got membership request with selfInfo that doesn't match the handshake")
   386  				return
   387  			}
   388  		}
   389  		g.forwardDiscoveryMsg(m)
   390  	}
   391  
   392  	if protoext.IsPullMsg(msg.GossipMessage) && protoext.GetPullMsgType(msg.GossipMessage) == pg.PullMsgType_IDENTITY_MSG {
   393  		g.certStore.handleMessage(m)
   394  	}
   395  }
   396  
   397  func (g *Node) forwardDiscoveryMsg(msg protoext.ReceivedMessage) {
   398  	g.discAdapter.incChan <- msg
   399  }
   400  
   401  // validateMsg checks the signature of the message if exists,
   402  // and also checks that the tag matches the message type
   403  func (g *Node) validateMsg(msg protoext.ReceivedMessage) bool {
   404  	if err := protoext.IsTagLegal(msg.GetGossipMessage().GossipMessage); err != nil {
   405  		g.logger.Warningf("Tag of %v isn't legal: %v", msg.GetGossipMessage(), errors.WithStack(err))
   406  		return false
   407  	}
   408  
   409  	if protoext.IsStateInfoMsg(msg.GetGossipMessage().GossipMessage) {
   410  		if err := g.validateStateInfoMsg(msg.GetGossipMessage()); err != nil {
   411  			g.logger.Warningf("StateInfo message %v is found invalid: %v", msg, err)
   412  			return false
   413  		}
   414  	}
   415  	return true
   416  }
   417  
   418  func (g *Node) sendGossipBatch(a []interface{}) {
   419  	msgs2Gossip := make([]*emittedGossipMessage, len(a))
   420  	for i, e := range a {
   421  		msgs2Gossip[i] = e.(*emittedGossipMessage)
   422  	}
   423  	g.gossipBatch(msgs2Gossip)
   424  }
   425  
   426  // gossipBatch - This is the method that actually decides to which peers to gossip the message
   427  // batch we possess.
   428  // For efficiency, we first isolate all the messages that have the same routing policy
   429  // and send them together, and only after that move to the next group of messages.
   430  // i.e: we send all blocks of channel C to the same group of peers,
   431  // and send all StateInfo messages to the same group of peers, etc. etc.
   432  // When we send blocks, we send only to peers that advertised themselves in the channel.
   433  // When we send StateInfo messages, we send to peers in the channel.
   434  // When we send messages that are marked to be sent only within the org, we send all of these messages
   435  // to the same set of peers.
   436  // The rest of the messages that have no restrictions on their destinations can be sent
   437  // to any group of peers.
   438  func (g *Node) gossipBatch(msgs []*emittedGossipMessage) {
   439  	if g.disc == nil {
   440  		g.logger.Error("Discovery has not been initialized yet, aborting!")
   441  		return
   442  	}
   443  
   444  	var blocks []*emittedGossipMessage
   445  	var stateInfoMsgs []*emittedGossipMessage
   446  	var orgMsgs []*emittedGossipMessage
   447  	var leadershipMsgs []*emittedGossipMessage
   448  
   449  	isABlock := func(o interface{}) bool {
   450  		return protoext.IsDataMsg(o.(*emittedGossipMessage).GossipMessage)
   451  	}
   452  	isAStateInfoMsg := func(o interface{}) bool {
   453  		return protoext.IsStateInfoMsg(o.(*emittedGossipMessage).GossipMessage)
   454  	}
   455  	aliveMsgsWithNoEndpointAndInOurOrg := func(o interface{}) bool {
   456  		msg := o.(*emittedGossipMessage)
   457  		if !protoext.IsAliveMsg(msg.GossipMessage) {
   458  			return false
   459  		}
   460  		member := msg.GetAliveMsg().Membership
   461  		return member.Endpoint == "" && g.IsInMyOrg(discovery.NetworkMember{PKIid: member.PkiId})
   462  	}
   463  	isOrgRestricted := func(o interface{}) bool {
   464  		return aliveMsgsWithNoEndpointAndInOurOrg(o) || protoext.IsOrgRestricted(o.(*emittedGossipMessage).GossipMessage)
   465  	}
   466  	isLeadershipMsg := func(o interface{}) bool {
   467  		return protoext.IsLeadershipMsg(o.(*emittedGossipMessage).GossipMessage)
   468  	}
   469  
   470  	// Gossip blocks
   471  	blocks, msgs = partitionMessages(isABlock, msgs)
   472  	g.gossipInChan(blocks, func(gc channel.GossipChannel) filter.RoutingFilter {
   473  		return filter.CombineRoutingFilters(gc.EligibleForChannel, gc.IsMemberInChan, g.IsInMyOrg)
   474  	})
   475  
   476  	// Gossip Leadership messages
   477  	leadershipMsgs, msgs = partitionMessages(isLeadershipMsg, msgs)
   478  	g.gossipInChan(leadershipMsgs, func(gc channel.GossipChannel) filter.RoutingFilter {
   479  		return filter.CombineRoutingFilters(gc.EligibleForChannel, gc.IsMemberInChan, g.IsInMyOrg)
   480  	})
   481  
   482  	// Gossip StateInfo messages
   483  	stateInfoMsgs, msgs = partitionMessages(isAStateInfoMsg, msgs)
   484  	for _, stateInfMsg := range stateInfoMsgs {
   485  		peerSelector := g.IsInMyOrg
   486  		gc := g.chanState.lookupChannelForGossipMsg(stateInfMsg.GossipMessage)
   487  		if gc != nil && g.hasExternalEndpoint(stateInfMsg.GossipMessage.GetStateInfo().PkiId) {
   488  			peerSelector = gc.IsMemberInChan
   489  		}
   490  
   491  		peerSelector = filter.CombineRoutingFilters(peerSelector, func(member discovery.NetworkMember) bool {
   492  			return stateInfMsg.filter(member.PKIid)
   493  		})
   494  
   495  		peers2Send := filter.SelectPeers(g.conf.PropagatePeerNum, g.disc.GetMembership(), peerSelector)
   496  		g.comm.Send(stateInfMsg.SignedGossipMessage, peers2Send...)
   497  	}
   498  
   499  	// Gossip messages restricted to our org
   500  	orgMsgs, msgs = partitionMessages(isOrgRestricted, msgs)
   501  	peers2Send := filter.SelectPeers(g.conf.PropagatePeerNum, g.disc.GetMembership(), g.IsInMyOrg)
   502  	for _, msg := range orgMsgs {
   503  		g.comm.Send(msg.SignedGossipMessage, g.removeSelfLoop(msg, peers2Send)...)
   504  	}
   505  
   506  	// Finally, gossip the remaining messages
   507  	for _, msg := range msgs {
   508  		if !protoext.IsAliveMsg(msg.GossipMessage) {
   509  			g.logger.Error("Unknown message type", msg)
   510  			continue
   511  		}
   512  		selectByOriginOrg := g.peersByOriginOrgPolicy(discovery.NetworkMember{PKIid: msg.GetAliveMsg().Membership.PkiId})
   513  		selector := filter.CombineRoutingFilters(selectByOriginOrg, func(member discovery.NetworkMember) bool {
   514  			return msg.filter(member.PKIid)
   515  		})
   516  		peers2Send := filter.SelectPeers(g.conf.PropagatePeerNum, g.disc.GetMembership(), selector)
   517  		g.sendAndFilterSecrets(msg.SignedGossipMessage, peers2Send...)
   518  	}
   519  }
   520  
   521  func (g *Node) sendAndFilterSecrets(msg *protoext.SignedGossipMessage, peers ...*comm.RemotePeer) {
   522  	for _, peer := range peers {
   523  		// Prevent forwarding alive messages of external organizations
   524  		// to peers that have no external endpoints
   525  		aliveMsgFromDiffOrg := protoext.IsAliveMsg(msg.GossipMessage) && !g.IsInMyOrg(discovery.NetworkMember{PKIid: msg.GetAliveMsg().Membership.PkiId})
   526  		if aliveMsgFromDiffOrg && !g.hasExternalEndpoint(peer.PKIID) {
   527  			continue
   528  		}
   529  
   530  		// Use cloned message to filter secrets to avoid data races when same message is sent multiple times
   531  		clonedMsg := &protoext.SignedGossipMessage{}
   532  		clonedMsg.GossipMessage = msg.GossipMessage
   533  		clonedMsg.Envelope = msg.Envelope
   534  
   535  		// Don't gossip secrets
   536  		if !g.IsInMyOrg(discovery.NetworkMember{PKIid: peer.PKIID}) {
   537  			clonedMsg.Envelope = proto.Clone(msg.Envelope).(*pg.Envelope) // clone the envelope
   538  			clonedMsg.Envelope.SecretEnvelope = nil
   539  		}
   540  		g.comm.Send(clonedMsg, peer)
   541  	}
   542  }
   543  
   544  // gossipInChan gossips a given GossipMessage slice according to a channel's routing policy.
   545  func (g *Node) gossipInChan(messages []*emittedGossipMessage, chanRoutingFactory channelRoutingFilterFactory) {
   546  	if len(messages) == 0 {
   547  		return
   548  	}
   549  	totalChannels := extractChannels(messages)
   550  	var channel common.ChannelID
   551  	var messagesOfChannel []*emittedGossipMessage
   552  	for len(totalChannels) > 0 {
   553  		// Take first channel
   554  		channel, totalChannels = totalChannels[0], totalChannels[1:]
   555  		// Extract all messages of that channel
   556  		grabMsgs := func(o interface{}) bool {
   557  			return bytes.Equal(o.(*emittedGossipMessage).Channel, channel)
   558  		}
   559  		messagesOfChannel, messages = partitionMessages(grabMsgs, messages)
   560  		if len(messagesOfChannel) == 0 {
   561  			continue
   562  		}
   563  		// Grab channel object for that channel
   564  		gc := g.chanState.getGossipChannelByChainID(channel)
   565  		if gc == nil {
   566  			g.logger.Warning("Channel", channel, "wasn't found")
   567  			continue
   568  		}
   569  		// Select the peers to send the messages to
   570  		// For leadership messages we will select all peers that pass routing factory - e.g. all peers in channel and org
   571  		membership := g.disc.GetMembership()
   572  		var peers2Send []*comm.RemotePeer
   573  		if protoext.IsLeadershipMsg(messagesOfChannel[0].GossipMessage) {
   574  			peers2Send = filter.SelectPeers(len(membership), membership, chanRoutingFactory(gc))
   575  		} else {
   576  			peers2Send = filter.SelectPeers(g.conf.PropagatePeerNum, membership, chanRoutingFactory(gc))
   577  		}
   578  
   579  		// Send the messages to the remote peers
   580  		for _, msg := range messagesOfChannel {
   581  			filteredPeers := g.removeSelfLoop(msg, peers2Send)
   582  			g.comm.Send(msg.SignedGossipMessage, filteredPeers...)
   583  		}
   584  	}
   585  }
   586  
   587  // removeSelfLoop deletes from the list of peers peer which has sent the message
   588  func (g *Node) removeSelfLoop(msg *emittedGossipMessage, peers []*comm.RemotePeer) []*comm.RemotePeer {
   589  	var result []*comm.RemotePeer
   590  	for _, peer := range peers {
   591  		if msg.filter(peer.PKIID) {
   592  			result = append(result, peer)
   593  		}
   594  	}
   595  	return result
   596  }
   597  
   598  // IdentityInfo returns information known peer identities
   599  func (g *Node) IdentityInfo() api.PeerIdentitySet {
   600  	return g.idMapper.IdentityInfo()
   601  }
   602  
   603  // SendByCriteria sends a given message to all peers that match the given SendCriteria
   604  func (g *Node) SendByCriteria(msg *protoext.SignedGossipMessage, criteria SendCriteria) error {
   605  	if criteria.MaxPeers == 0 {
   606  		return nil
   607  	}
   608  	if criteria.Timeout == 0 {
   609  		return errors.New("Timeout should be specified")
   610  	}
   611  
   612  	if criteria.IsEligible == nil {
   613  		criteria.IsEligible = filter.SelectAllPolicy
   614  	}
   615  
   616  	membership := g.disc.GetMembership()
   617  
   618  	if len(criteria.Channel) > 0 {
   619  		gc := g.chanState.getGossipChannelByChainID(criteria.Channel)
   620  		if gc == nil {
   621  			return fmt.Errorf("Requested to Send for channel %s, but no such channel exists", string(criteria.Channel))
   622  		}
   623  		membership = gc.GetPeers()
   624  	}
   625  
   626  	peers2send := filter.SelectPeers(criteria.MaxPeers, membership, criteria.IsEligible)
   627  	if len(peers2send) < criteria.MinAck {
   628  		return fmt.Errorf("Requested to send to at least %d peers, but know only of %d suitable peers", criteria.MinAck, len(peers2send))
   629  	}
   630  
   631  	results := g.comm.SendWithAck(msg, criteria.Timeout, criteria.MinAck, peers2send...)
   632  
   633  	for _, res := range results {
   634  		if res.Error() == "" {
   635  			continue
   636  		}
   637  		g.logger.Warning("Failed sending to", res.Endpoint, "error:", res.Error())
   638  	}
   639  
   640  	if results.AckCount() < criteria.MinAck {
   641  		return errors.New(results.String())
   642  	}
   643  	return nil
   644  }
   645  
   646  // Gossip sends a message to other peers to the network
   647  func (g *Node) Gossip(msg *pg.GossipMessage) {
   648  	// Educate developers to Gossip messages with the right tags.
   649  	// See IsTagLegal() for wanted behavior.
   650  	if err := protoext.IsTagLegal(msg); err != nil {
   651  		panic(errors.WithStack(err))
   652  	}
   653  
   654  	sMsg := &protoext.SignedGossipMessage{
   655  		GossipMessage: msg,
   656  	}
   657  
   658  	var err error
   659  	if protoext.IsDataMsg(sMsg.GossipMessage) {
   660  		sMsg, err = protoext.NoopSign(sMsg.GossipMessage)
   661  	} else {
   662  		_, err = sMsg.Sign(func(msg []byte) ([]byte, error) {
   663  			return g.mcs.Sign(msg)
   664  		})
   665  	}
   666  
   667  	if err != nil {
   668  		g.logger.Warningf("Failed signing message: %+v", errors.WithStack(err))
   669  		return
   670  	}
   671  
   672  	if protoext.IsChannelRestricted(msg) {
   673  		gc := g.chanState.getGossipChannelByChainID(msg.Channel)
   674  		if gc == nil {
   675  			g.logger.Warning("Failed obtaining gossipChannel of", msg.Channel, "aborting")
   676  			return
   677  		}
   678  		if protoext.IsDataMsg(msg) {
   679  			gc.AddToMsgStore(sMsg)
   680  		}
   681  	}
   682  
   683  	if g.conf.PropagateIterations == 0 {
   684  		return
   685  	}
   686  	g.emitter.Add(&emittedGossipMessage{
   687  		SignedGossipMessage: sMsg,
   688  		filter: func(_ common.PKIidType) bool {
   689  			return true
   690  		},
   691  	})
   692  }
   693  
   694  // Send sends a message to remote peers
   695  func (g *Node) Send(msg *pg.GossipMessage, peers ...*comm.RemotePeer) {
   696  	m, err := protoext.NoopSign(msg)
   697  	if err != nil {
   698  		g.logger.Warningf("Failed creating SignedGossipMessage: %+v", errors.WithStack(err))
   699  		return
   700  	}
   701  	g.comm.Send(m, peers...)
   702  }
   703  
   704  // Peers returns the current alive NetworkMembers
   705  func (g *Node) Peers() []discovery.NetworkMember {
   706  	return g.disc.GetMembership()
   707  }
   708  
   709  // PeersOfChannel returns the NetworkMembers considered alive
   710  // and also subscribed to the channel given
   711  func (g *Node) PeersOfChannel(channel common.ChannelID) []discovery.NetworkMember {
   712  	gc := g.chanState.getGossipChannelByChainID(channel)
   713  	if gc == nil {
   714  		g.logger.Debug("No such channel", channel)
   715  		return nil
   716  	}
   717  
   718  	return gc.GetPeers()
   719  }
   720  
   721  // SelfMembershipInfo returns the peer's membership information
   722  func (g *Node) SelfMembershipInfo() discovery.NetworkMember {
   723  	return g.disc.Self()
   724  }
   725  
   726  // SelfChannelInfo returns the peer's latest StateInfo message of a given channel
   727  func (g *Node) SelfChannelInfo(chain common.ChannelID) *protoext.SignedGossipMessage {
   728  	ch := g.chanState.getGossipChannelByChainID(chain)
   729  	if ch == nil {
   730  		return nil
   731  	}
   732  	return ch.Self()
   733  }
   734  
   735  // PeerFilter receives a SubChannelSelectionCriteria and returns a RoutingFilter that selects
   736  // only peer identities that match the given criteria, and that they published their channel participation
   737  func (g *Node) PeerFilter(channel common.ChannelID, messagePredicate api.SubChannelSelectionCriteria) (filter.RoutingFilter, error) {
   738  	gc := g.chanState.getGossipChannelByChainID(channel)
   739  	if gc == nil {
   740  		return nil, errors.Errorf("Channel %s doesn't exist", string(channel))
   741  	}
   742  	return gc.PeerFilter(messagePredicate), nil
   743  }
   744  
   745  // Stop stops the gossip component
   746  func (g *Node) Stop() {
   747  	if g.toDie() {
   748  		return
   749  	}
   750  	atomic.StoreInt32(&g.stopFlag, int32(1))
   751  	g.logger.Info("Stopping gossip")
   752  	close(g.toDieChan)
   753  	g.stopSignal.Wait()
   754  	g.chanState.stop()
   755  	g.discAdapter.close()
   756  	g.disc.Stop()
   757  	g.certStore.stop()
   758  	g.emitter.Stop()
   759  	g.ChannelDeMultiplexer.Close()
   760  	g.stateInfoMsgStore.Stop()
   761  	g.comm.Stop()
   762  }
   763  
   764  // UpdateMetadata updates gossip membership metadata.
   765  func (g *Node) UpdateMetadata(md []byte) {
   766  	g.disc.UpdateMetadata(md)
   767  }
   768  
   769  // UpdateLedgerHeight updates the ledger height the peer
   770  // publishes to other peers in the channel
   771  func (g *Node) UpdateLedgerHeight(height uint64, channelID common.ChannelID) {
   772  	gc := g.chanState.getGossipChannelByChainID(channelID)
   773  	if gc == nil {
   774  		g.logger.Warning("No such channel", channelID)
   775  		return
   776  	}
   777  	gc.UpdateLedgerHeight(height)
   778  }
   779  
   780  // UpdateChaincodes updates the chaincodes the peer publishes
   781  // to other peers in the channel
   782  func (g *Node) UpdateChaincodes(chaincodes []*pg.Chaincode, channelID common.ChannelID) {
   783  	gc := g.chanState.getGossipChannelByChainID(channelID)
   784  	if gc == nil {
   785  		g.logger.Warning("No such channel", channelID)
   786  		return
   787  	}
   788  	gc.UpdateChaincodes(chaincodes)
   789  }
   790  
   791  // Accept returns a dedicated read-only channel for messages sent by other nodes that match a certain predicate.
   792  // If passThrough is false, the messages are processed by the gossip layer beforehand.
   793  // If passThrough is true, the gossip layer doesn't intervene and the messages
   794  // can be used to send a reply back to the sender
   795  func (g *Node) Accept(acceptor common.MessageAcceptor, passThrough bool) (<-chan *pg.GossipMessage, <-chan protoext.ReceivedMessage) {
   796  	if passThrough {
   797  		return nil, g.comm.Accept(acceptor)
   798  	}
   799  	acceptByType := func(o interface{}) bool {
   800  		if o, isGossipMsg := o.(*pg.GossipMessage); isGossipMsg {
   801  			return acceptor(o)
   802  		}
   803  		if o, isSignedMsg := o.(*protoext.SignedGossipMessage); isSignedMsg {
   804  			sMsg := o
   805  			return acceptor(sMsg.GossipMessage)
   806  		}
   807  		g.logger.Warning("Message type:", reflect.TypeOf(o), "cannot be evaluated")
   808  		return false
   809  	}
   810  	inCh := g.AddChannel(acceptByType)
   811  	outCh := make(chan *pg.GossipMessage, acceptChanSize)
   812  	go func() {
   813  		defer close(outCh)
   814  		for {
   815  			select {
   816  			case <-g.toDieChan:
   817  				return
   818  			case m, channelOpen := <-inCh:
   819  				if !channelOpen {
   820  					return
   821  				}
   822  				select {
   823  				case <-g.toDieChan:
   824  					return
   825  				case outCh <- m.(*protoext.SignedGossipMessage).GossipMessage:
   826  				}
   827  			}
   828  		}
   829  	}()
   830  	return outCh, nil
   831  }
   832  
   833  func selectOnlyDiscoveryMessages(m interface{}) bool {
   834  	msg, isGossipMsg := m.(protoext.ReceivedMessage)
   835  	if !isGossipMsg {
   836  		return false
   837  	}
   838  	alive := msg.GetGossipMessage().GetAliveMsg()
   839  	memRes := msg.GetGossipMessage().GetMemRes()
   840  	memReq := msg.GetGossipMessage().GetMemReq()
   841  
   842  	selected := alive != nil || memReq != nil || memRes != nil
   843  
   844  	return selected
   845  }
   846  
   847  func (g *Node) newDiscoveryAdapter() *discoveryAdapter {
   848  	return &discoveryAdapter{
   849  		c:        g.comm,
   850  		stopping: int32(0),
   851  		gossipFunc: func(msg *protoext.SignedGossipMessage) {
   852  			if g.conf.PropagateIterations == 0 {
   853  				return
   854  			}
   855  			g.emitter.Add(&emittedGossipMessage{
   856  				SignedGossipMessage: msg,
   857  				filter: func(_ common.PKIidType) bool {
   858  					return true
   859  				},
   860  			})
   861  		},
   862  		forwardFunc: func(message protoext.ReceivedMessage) {
   863  			if g.conf.PropagateIterations == 0 {
   864  				return
   865  			}
   866  			g.emitter.Add(&emittedGossipMessage{
   867  				SignedGossipMessage: message.GetGossipMessage(),
   868  				filter:              message.GetConnectionInfo().ID.IsNotSameFilter,
   869  			})
   870  		},
   871  		incChan:          make(chan protoext.ReceivedMessage),
   872  		presumedDead:     g.presumedDead,
   873  		disclosurePolicy: g.disclosurePolicy,
   874  	}
   875  }
   876  
   877  // discoveryAdapter is used to supply the discovery module with needed abilities
   878  // that the comm interface in the discovery module declares
   879  type discoveryAdapter struct {
   880  	stopping         int32
   881  	c                comm.Comm
   882  	presumedDead     chan common.PKIidType
   883  	incChan          chan protoext.ReceivedMessage
   884  	gossipFunc       func(message *protoext.SignedGossipMessage)
   885  	forwardFunc      func(message protoext.ReceivedMessage)
   886  	disclosurePolicy discovery.DisclosurePolicy
   887  }
   888  
   889  func (da *discoveryAdapter) close() {
   890  	atomic.StoreInt32(&da.stopping, int32(1))
   891  	close(da.incChan)
   892  }
   893  
   894  func (da *discoveryAdapter) toDie() bool {
   895  	return atomic.LoadInt32(&da.stopping) == int32(1)
   896  }
   897  
   898  func (da *discoveryAdapter) Gossip(msg *protoext.SignedGossipMessage) {
   899  	if da.toDie() {
   900  		return
   901  	}
   902  
   903  	da.gossipFunc(msg)
   904  }
   905  
   906  func (da *discoveryAdapter) Forward(msg protoext.ReceivedMessage) {
   907  	if da.toDie() {
   908  		return
   909  	}
   910  
   911  	da.forwardFunc(msg)
   912  }
   913  
   914  func (da *discoveryAdapter) SendToPeer(peer *discovery.NetworkMember, msg *protoext.SignedGossipMessage) {
   915  	if da.toDie() {
   916  		return
   917  	}
   918  	// Check membership requests for peers that we know of their PKI-ID.
   919  	// The only peers we don't know about their PKI-IDs are bootstrap peers.
   920  	if memReq := msg.GetMemReq(); memReq != nil && len(peer.PKIid) != 0 {
   921  		selfMsg, err := protoext.EnvelopeToGossipMessage(memReq.SelfInformation)
   922  		if err != nil {
   923  			// Shouldn't happen
   924  			panic(errors.Wrapf(err, "Tried to send a membership request with a malformed AliveMessage"))
   925  		}
   926  		// Apply the EnvelopeFilter of the disclosure policy
   927  		// on the alive message of the selfInfo field of the membership request
   928  		_, omitConcealedFields := da.disclosurePolicy(peer)
   929  		selfMsg.Envelope = omitConcealedFields(selfMsg)
   930  		// Backup old known field
   931  		oldKnown := memReq.Known
   932  		// Override new SelfInfo message with updated envelope
   933  		memReq = &pg.MembershipRequest{
   934  			SelfInformation: selfMsg.Envelope,
   935  			Known:           oldKnown,
   936  		}
   937  		msgCopy := proto.Clone(msg.GossipMessage).(*pg.GossipMessage)
   938  
   939  		// Update original message
   940  		msgCopy.Content = &pg.GossipMessage_MemReq{
   941  			MemReq: memReq,
   942  		}
   943  		// Update the envelope of the outer message, no need to sign (point2point)
   944  		msg, err = protoext.NoopSign(msgCopy)
   945  		if err != nil {
   946  			return
   947  		}
   948  		da.c.Send(msg, &comm.RemotePeer{PKIID: peer.PKIid, Endpoint: peer.PreferredEndpoint()})
   949  		return
   950  	}
   951  	da.c.Send(msg, &comm.RemotePeer{PKIID: peer.PKIid, Endpoint: peer.PreferredEndpoint()})
   952  }
   953  
   954  func (da *discoveryAdapter) Ping(peer *discovery.NetworkMember) bool {
   955  	err := da.c.Probe(&comm.RemotePeer{Endpoint: peer.PreferredEndpoint(), PKIID: peer.PKIid})
   956  	return err == nil
   957  }
   958  
   959  func (da *discoveryAdapter) Accept() <-chan protoext.ReceivedMessage {
   960  	return da.incChan
   961  }
   962  
   963  func (da *discoveryAdapter) PresumedDead() <-chan common.PKIidType {
   964  	return da.presumedDead
   965  }
   966  
   967  func (da *discoveryAdapter) IdentitySwitch() <-chan common.PKIidType {
   968  	return da.c.IdentitySwitch()
   969  }
   970  
   971  func (da *discoveryAdapter) CloseConn(peer *discovery.NetworkMember) {
   972  	da.c.CloseConn(&comm.RemotePeer{PKIID: peer.PKIid})
   973  }
   974  
   975  type discoverySecurityAdapter struct {
   976  	identity              api.PeerIdentityType
   977  	includeIdentityPeriod time.Time
   978  	idMapper              identity.Mapper
   979  	sa                    api.SecurityAdvisor
   980  	mcs                   api.MessageCryptoService
   981  	c                     comm.Comm
   982  	logger                util.Logger
   983  }
   984  
   985  func (g *Node) newDiscoverySecurityAdapter() *discoverySecurityAdapter {
   986  	return &discoverySecurityAdapter{
   987  		sa:                    g.secAdvisor,
   988  		idMapper:              g.idMapper,
   989  		mcs:                   g.mcs,
   990  		c:                     g.comm,
   991  		logger:                g.logger,
   992  		includeIdentityPeriod: g.includeIdentityPeriod,
   993  		identity:              g.selfIdentity,
   994  	}
   995  }
   996  
   997  // validateAliveMsg validates that an Alive message is authentic
   998  func (sa *discoverySecurityAdapter) ValidateAliveMsg(m *protoext.SignedGossipMessage) bool {
   999  	am := m.GetAliveMsg()
  1000  	if am == nil || am.Membership == nil || am.Membership.PkiId == nil || !m.IsSigned() {
  1001  		sa.logger.Warning("Invalid alive message:", m)
  1002  		return false
  1003  	}
  1004  
  1005  	var identity api.PeerIdentityType
  1006  
  1007  	// If identity is included inside AliveMessage
  1008  	if am.Identity != nil {
  1009  		identity = api.PeerIdentityType(am.Identity)
  1010  		claimedPKIID := am.Membership.PkiId
  1011  		err := sa.idMapper.Put(claimedPKIID, identity)
  1012  		if err != nil {
  1013  			sa.logger.Debugf("Failed validating identity of %v reason: %+v", am, errors.WithStack(err))
  1014  			return false
  1015  		}
  1016  	} else {
  1017  		identity, _ = sa.idMapper.Get(am.Membership.PkiId)
  1018  		if identity != nil {
  1019  			sa.logger.Debug("Fetched identity of", protoext.MemberToString(am.Membership), "from identity store")
  1020  		}
  1021  	}
  1022  
  1023  	if identity == nil {
  1024  		sa.logger.Debug("Don't have certificate for", am)
  1025  		return false
  1026  	}
  1027  
  1028  	return sa.validateAliveMsgSignature(m, identity)
  1029  }
  1030  
  1031  // SignMessage signs an AliveMessage and updates its signature field
  1032  func (sa *discoverySecurityAdapter) SignMessage(m *pg.GossipMessage, internalEndpoint string) *pg.Envelope {
  1033  	signer := func(msg []byte) ([]byte, error) {
  1034  		return sa.mcs.Sign(msg)
  1035  	}
  1036  	if protoext.IsAliveMsg(m) && time.Now().Before(sa.includeIdentityPeriod) {
  1037  		m.GetAliveMsg().Identity = sa.identity
  1038  	}
  1039  	sMsg := &protoext.SignedGossipMessage{
  1040  		GossipMessage: m,
  1041  	}
  1042  	e, err := sMsg.Sign(signer)
  1043  	if err != nil {
  1044  		sa.logger.Warningf("Failed signing message: %+v", errors.WithStack(err))
  1045  		return nil
  1046  	}
  1047  
  1048  	if internalEndpoint == "" {
  1049  		return e
  1050  	}
  1051  	protoext.SignSecret(e, signer, &pg.Secret{
  1052  		Content: &pg.Secret_InternalEndpoint{
  1053  			InternalEndpoint: internalEndpoint,
  1054  		},
  1055  	})
  1056  	return e
  1057  }
  1058  
  1059  func (sa *discoverySecurityAdapter) validateAliveMsgSignature(m *protoext.SignedGossipMessage, identity api.PeerIdentityType) bool {
  1060  	am := m.GetAliveMsg()
  1061  	// At this point we got the certificate of the peer, proceed to verifying the AliveMessage
  1062  	verifier := func(peerIdentity []byte, signature, message []byte) error {
  1063  		return sa.mcs.Verify(api.PeerIdentityType(peerIdentity), signature, message)
  1064  	}
  1065  
  1066  	// We verify the signature on the message
  1067  	err := m.Verify(identity, verifier)
  1068  	if err != nil {
  1069  		sa.logger.Warningf("Failed verifying: %v: %+v", am, errors.WithStack(err))
  1070  		return false
  1071  	}
  1072  
  1073  	return true
  1074  }
  1075  
  1076  func (g *Node) createCertStorePuller() pull.Mediator {
  1077  	conf := pull.Config{
  1078  		MsgType:           pg.PullMsgType_IDENTITY_MSG,
  1079  		Channel:           []byte(""),
  1080  		ID:                g.conf.InternalEndpoint,
  1081  		PeerCountToSelect: g.conf.PullPeerNum,
  1082  		PullInterval:      g.conf.PullInterval,
  1083  		Tag:               pg.GossipMessage_EMPTY,
  1084  		PullEngineConfig: algo.PullEngineConfig{
  1085  			DigestWaitTime:   g.conf.DigestWaitTime,
  1086  			RequestWaitTime:  g.conf.RequestWaitTime,
  1087  			ResponseWaitTime: g.conf.ResponseWaitTime,
  1088  		},
  1089  	}
  1090  	pkiIDFromMsg := func(msg *protoext.SignedGossipMessage) string {
  1091  		identityMsg := msg.GetPeerIdentity()
  1092  		if identityMsg == nil || identityMsg.PkiId == nil {
  1093  			return ""
  1094  		}
  1095  		return fmt.Sprintf("%s", string(identityMsg.PkiId))
  1096  	}
  1097  	certConsumer := func(msg *protoext.SignedGossipMessage) {
  1098  		idMsg := msg.GetPeerIdentity()
  1099  		if idMsg == nil || idMsg.Cert == nil || idMsg.PkiId == nil {
  1100  			g.logger.Warning("Invalid PeerIdentity:", idMsg)
  1101  			return
  1102  		}
  1103  		err := g.idMapper.Put(common.PKIidType(idMsg.PkiId), api.PeerIdentityType(idMsg.Cert))
  1104  		if err != nil {
  1105  			g.logger.Warningf("Failed associating PKI-ID with certificate: %+v", errors.WithStack(err))
  1106  		}
  1107  		g.logger.Debug("Learned of a new certificate:", idMsg.Cert)
  1108  	}
  1109  	adapter := &pull.PullAdapter{
  1110  		Sndr:            g.comm,
  1111  		MemSvc:          g.disc,
  1112  		IdExtractor:     pkiIDFromMsg,
  1113  		MsgCons:         certConsumer,
  1114  		EgressDigFilter: g.sameOrgOrOurOrgPullFilter,
  1115  	}
  1116  	return pull.NewPullMediator(conf, adapter)
  1117  }
  1118  
  1119  func (g *Node) sameOrgOrOurOrgPullFilter(msg protoext.ReceivedMessage) func(string) bool {
  1120  	peersOrg := g.secAdvisor.OrgByPeerIdentity(msg.GetConnectionInfo().Identity)
  1121  	if len(peersOrg) == 0 {
  1122  		g.logger.Warning("Failed determining organization of", msg.GetConnectionInfo())
  1123  		return func(_ string) bool {
  1124  			return false
  1125  		}
  1126  	}
  1127  
  1128  	// If the peer is from our org, gossip all identities
  1129  	if bytes.Equal(g.selfOrg, peersOrg) {
  1130  		return func(_ string) bool {
  1131  			return true
  1132  		}
  1133  	}
  1134  	// Else, the peer is from a different org
  1135  	return func(item string) bool {
  1136  		pkiID := common.PKIidType(item)
  1137  		msgsOrg := g.getOrgOfPeer(pkiID)
  1138  		if len(msgsOrg) == 0 {
  1139  			g.logger.Warning("Failed determining organization of", pkiID)
  1140  			return false
  1141  		}
  1142  		// Don't gossip identities of dead peers or of peers
  1143  		// without external endpoints, to peers of foreign organizations.
  1144  		if !g.hasExternalEndpoint(pkiID) {
  1145  			return false
  1146  		}
  1147  		// Peer from our org or identity from our org or identity from peer's org
  1148  		return bytes.Equal(msgsOrg, g.selfOrg) || bytes.Equal(msgsOrg, peersOrg)
  1149  	}
  1150  }
  1151  
  1152  func (g *Node) connect2BootstrapPeers() {
  1153  	for _, endpoint := range g.conf.BootstrapPeers {
  1154  		endpoint := endpoint
  1155  		identifier := func() (*discovery.PeerIdentification, error) {
  1156  			remotePeerIdentity, err := g.comm.Handshake(&comm.RemotePeer{Endpoint: endpoint})
  1157  			if err != nil {
  1158  				return nil, errors.WithStack(err)
  1159  			}
  1160  			sameOrg := bytes.Equal(g.selfOrg, g.secAdvisor.OrgByPeerIdentity(remotePeerIdentity))
  1161  			if !sameOrg {
  1162  				return nil, errors.Errorf("%s isn't in our organization, cannot be a bootstrap peer", endpoint)
  1163  			}
  1164  			pkiID := g.mcs.GetPKIidOfCert(remotePeerIdentity)
  1165  			if len(pkiID) == 0 {
  1166  				return nil, errors.Errorf("Wasn't able to extract PKI-ID of remote peer with identity of %v", remotePeerIdentity)
  1167  			}
  1168  			return &discovery.PeerIdentification{ID: pkiID, SelfOrg: sameOrg}, nil
  1169  		}
  1170  		g.disc.Connect(discovery.NetworkMember{
  1171  			InternalEndpoint: endpoint,
  1172  			Endpoint:         endpoint,
  1173  		}, identifier)
  1174  	}
  1175  
  1176  }
  1177  
  1178  func (g *Node) hasExternalEndpoint(PKIID common.PKIidType) bool {
  1179  	if nm := g.disc.Lookup(PKIID); nm != nil {
  1180  		return nm.Endpoint != ""
  1181  	}
  1182  	return false
  1183  }
  1184  
  1185  // IsInMyOrg checks whether a network member is in this peer's org
  1186  func (g *Node) IsInMyOrg(member discovery.NetworkMember) bool {
  1187  	if member.PKIid == nil {
  1188  		return false
  1189  	}
  1190  	if org := g.getOrgOfPeer(member.PKIid); org != nil {
  1191  		return bytes.Equal(g.selfOrg, org)
  1192  	}
  1193  	return false
  1194  }
  1195  
  1196  func (g *Node) getOrgOfPeer(PKIID common.PKIidType) api.OrgIdentityType {
  1197  	cert, err := g.idMapper.Get(PKIID)
  1198  	if err != nil {
  1199  		return nil
  1200  	}
  1201  
  1202  	return g.secAdvisor.OrgByPeerIdentity(cert)
  1203  }
  1204  
  1205  func (g *Node) validateLeadershipMessage(msg *protoext.SignedGossipMessage) error {
  1206  	pkiID := msg.GetLeadershipMsg().PkiId
  1207  	if len(pkiID) == 0 {
  1208  		return errors.New("Empty PKI-ID")
  1209  	}
  1210  	identity, err := g.idMapper.Get(pkiID)
  1211  	if err != nil {
  1212  		return errors.Wrap(err, "Unable to fetch PKI-ID from id-mapper")
  1213  	}
  1214  	return msg.Verify(identity, func(peerIdentity []byte, signature, message []byte) error {
  1215  		return g.mcs.Verify(identity, signature, message)
  1216  	})
  1217  }
  1218  
  1219  func (g *Node) validateStateInfoMsg(msg *protoext.SignedGossipMessage) error {
  1220  	verifier := func(identity []byte, signature, message []byte) error {
  1221  		pkiID := g.idMapper.GetPKIidOfCert(api.PeerIdentityType(identity))
  1222  		if pkiID == nil {
  1223  			return errors.New("PKI-ID not found in identity mapper")
  1224  		}
  1225  		return g.idMapper.Verify(pkiID, signature, message)
  1226  	}
  1227  	identity, err := g.idMapper.Get(msg.GetStateInfo().PkiId)
  1228  	if err != nil {
  1229  		return errors.WithStack(err)
  1230  	}
  1231  	return msg.Verify(identity, verifier)
  1232  }
  1233  
  1234  func (g *Node) disclosurePolicy(remotePeer *discovery.NetworkMember) (discovery.Sieve, discovery.EnvelopeFilter) {
  1235  	remotePeerOrg := g.getOrgOfPeer(remotePeer.PKIid)
  1236  
  1237  	if len(remotePeerOrg) == 0 {
  1238  		g.logger.Warning("Cannot determine organization of", remotePeer)
  1239  		return func(msg *protoext.SignedGossipMessage) bool {
  1240  				return false
  1241  			}, func(msg *protoext.SignedGossipMessage) *pg.Envelope {
  1242  				return msg.Envelope
  1243  			}
  1244  	}
  1245  
  1246  	return func(msg *protoext.SignedGossipMessage) bool {
  1247  			if !protoext.IsAliveMsg(msg.GossipMessage) {
  1248  				g.logger.Panic("Programming error, this should be used only on alive messages")
  1249  			}
  1250  			org := g.getOrgOfPeer(msg.GetAliveMsg().Membership.PkiId)
  1251  			if len(org) == 0 {
  1252  				g.logger.Warning("Unable to determine org of message", msg.GossipMessage)
  1253  				// Don't disseminate messages who's origin org is unknown
  1254  				return false
  1255  			}
  1256  
  1257  			// Target org and the message are from the same org
  1258  			fromSameForeignOrg := bytes.Equal(remotePeerOrg, org)
  1259  			// The message is from my org
  1260  			fromMyOrg := bytes.Equal(g.selfOrg, org)
  1261  			// Forward to target org only messages from our org, or from the target org itself.
  1262  			if !(fromSameForeignOrg || fromMyOrg) {
  1263  				return false
  1264  			}
  1265  
  1266  			// Pass the alive message only if the alive message is in the same org as the remote peer
  1267  			// or the message has an external endpoint, and the remote peer also has one
  1268  			return bytes.Equal(org, remotePeerOrg) || msg.GetAliveMsg().Membership.Endpoint != "" && remotePeer.Endpoint != ""
  1269  		}, func(msg *protoext.SignedGossipMessage) *pg.Envelope {
  1270  			envelope := proto.Clone(msg.Envelope).(*pg.Envelope)
  1271  			if !bytes.Equal(g.selfOrg, remotePeerOrg) {
  1272  				envelope.SecretEnvelope = nil
  1273  			}
  1274  			return envelope
  1275  		}
  1276  }
  1277  
  1278  func (g *Node) peersByOriginOrgPolicy(peer discovery.NetworkMember) filter.RoutingFilter {
  1279  	peersOrg := g.getOrgOfPeer(peer.PKIid)
  1280  	if len(peersOrg) == 0 {
  1281  		g.logger.Warning("Unable to determine organization of peer", peer)
  1282  		// Don't disseminate messages who's origin org is undetermined
  1283  		return filter.SelectNonePolicy
  1284  	}
  1285  
  1286  	if bytes.Equal(g.selfOrg, peersOrg) {
  1287  		// Disseminate messages from our org to all known organizations.
  1288  		// IMPORTANT: Currently a peer cannot un-join a channel, so the only way
  1289  		// of making gossip stop talking to an organization is by having the MSP
  1290  		// refuse validating messages from it.
  1291  		return filter.SelectAllPolicy
  1292  	}
  1293  
  1294  	// Else, select peers from the origin's organization,
  1295  	// and also peers from our own organization
  1296  	return func(member discovery.NetworkMember) bool {
  1297  		memberOrg := g.getOrgOfPeer(member.PKIid)
  1298  		if len(memberOrg) == 0 {
  1299  			return false
  1300  		}
  1301  		isFromMyOrg := bytes.Equal(g.selfOrg, memberOrg)
  1302  		return isFromMyOrg || bytes.Equal(memberOrg, peersOrg)
  1303  	}
  1304  }
  1305  
  1306  // partitionMessages receives a predicate and a slice of gossip messages
  1307  // and returns a tuple of two slices: the messages that hold for the predicate
  1308  // and the rest
  1309  func partitionMessages(pred common.MessageAcceptor, a []*emittedGossipMessage) ([]*emittedGossipMessage, []*emittedGossipMessage) {
  1310  	s1 := []*emittedGossipMessage{}
  1311  	s2 := []*emittedGossipMessage{}
  1312  	for _, m := range a {
  1313  		if pred(m) {
  1314  			s1 = append(s1, m)
  1315  		} else {
  1316  			s2 = append(s2, m)
  1317  		}
  1318  	}
  1319  	return s1, s2
  1320  }
  1321  
  1322  // extractChannels returns a slice with all channels
  1323  // of all given GossipMessages
  1324  func extractChannels(a []*emittedGossipMessage) []common.ChannelID {
  1325  	channels := []common.ChannelID{}
  1326  	for _, m := range a {
  1327  		if len(m.Channel) == 0 {
  1328  			continue
  1329  		}
  1330  		sameChan := func(a interface{}, b interface{}) bool {
  1331  			return bytes.Equal(a.(common.ChannelID), b.(common.ChannelID))
  1332  		}
  1333  		if util.IndexInSlice(channels, common.ChannelID(m.Channel), sameChan) == -1 {
  1334  			channels = append(channels, common.ChannelID(m.Channel))
  1335  		}
  1336  	}
  1337  	return channels
  1338  }