// NewGossipService creates a gossip instance attached to a gRPC server
966315
func NewGossipService(conf *Config, s *grpc.Server, sa api.SecurityAdvisor,
	mcs api.MessageCryptoService, selfIdentity api.PeerIdentityType,
	secureDialOpts api.PeerSecureDialOpts, gossipMetrics *metrics.GossipMetrics) Gossip {
	var err error

	lgr := util.GetLogger(util.GossipLogger, conf.ID)

	g := &gossipServiceImpl{
		selfOrg:               sa.OrgByPeerIdentity(selfIdentity),
		secAdvisor:            sa,
		selfIdentity:          selfIdentity,
		presumedDead:          make(chan common.PKIidType, presumedDeadChanSize),
		disc:                  nil,
		mcs:                   mcs,
		conf:                  conf,
		ChannelDeMultiplexer:  comm.NewChannelDemultiplexer(),
		logger:                lgr,
		toDieChan:             make(chan struct{}, 1),
		stopFlag:              int32(0),
		stopSignal:            &sync.WaitGroup{},
		includeIdentityPeriod: time.Now().Add(conf.PublishCertPeriod),
		gossipMetrics:         gossipMetrics,
	}
	g.stateInfoMsgStore = g.newStateInfoMsgStore()

	g.idMapper = identity.NewIdentityMapper(mcs, selfIdentity, func(pkiID common.PKIidType, identity api.PeerIdentityType) {
		g.comm.CloseConn(&comm.RemotePeer{PKIID: pkiID})
		g.certPuller.Remove(string(pkiID))
	}, sa)

	commConfig := comm.CommConfig{
		DialTimeout:  conf.DialTimeout,
		ConnTimeout:  conf.ConnTimeout,
		RecvBuffSize: conf.RecvBuffSize,
		SendBuffSize: conf.SendBuffSize,
	}
	g.comm, err = comm.NewCommInstance(s, conf.TLSCerts, g.idMapper, selfIdentity, secureDialOpts, sa,
		gossipMetrics.CommMetrics, commConfig)

	if err != nil {
		lgr.Error("Failed instntiating communication layer:", err)
		return nil
	}

	g.chanState = newChannelState(g)
	g.emitter = newBatchingEmitter(conf.PropagateIterations,
		conf.MaxPropagationBurstSize, conf.MaxPropagationBurstLatency,
		g.sendGossipBatch)

	g.discAdapter = g.newDiscoveryAdapter()
	g.disSecAdap = g.newDiscoverySecurityAdapter()

	discoveryConfig := discovery.DiscoveryConfig{
		AliveTimeInterval:            conf.AliveTimeInterval,
		AliveExpirationTimeout:       conf.AliveExpirationTimeout,
		AliveExpirationCheckInterval: conf.AliveExpirationCheckInterval,
		ReconnectInterval:            conf.ReconnectInterval,
	}
	g.disc = discovery.NewDiscoveryService(g.selfNetworkMember(), g.discAdapter, g.disSecAdap, g.disclosurePolicy,
		discoveryConfig)
	g.logger.Infof("Creating gossip service with self membership of %s", g.selfNetworkMember())

	g.certPuller = g.createCertStorePuller()
	g.certStore = newCertStore(g.certPuller, g.idMapper, selfIdentity, mcs)

	if g.conf.ExternalEndpoint == "" {
		g.logger.Warning("External endpoint is empty, peer will not be accessible outside of its organization")
	}
	// Adding delta for handlePresumedDead and
	// acceptMessages goRoutines to block on Wait
	g.stopSignal.Add(2)
	go g.start()
	go g.connect2BootstrapPeers()

	return g
}
1102522
func (p *peer) OnGossip(buf []byte) (delta mesh.GossipData, err error) {
	message, err := DecodeKVState(buf)
	if err != nil {
		glog.Warningf("error decoding OnGossip: %v", err)
		return nil, err
	}

	deltas := &KVState{}
	p.st.merge(message, deltas)

	if len(deltas.Records) == 0 {
		// per OnGossip requirements
		glog.V(4).Infof("OnGossip %v => delta empty", message)
		return nil, nil
	} else {
		glog.V(4).Infof("OnGossip %v => delta %v", message, deltas)
		return deltas, nil
	}
}
33972
func NewMockGitilesServer(ctrl *gomock.Controller) *MockGitilesServer {
	mock := &MockGitilesServer{ctrl: ctrl}
	mock.recorder = &MockGitilesServerMockRecorder{mock}
	return mock
}
672432
func newMsgEventer(rw MsgReadWriter, feed *event.Feed, peerID enode.ID, proto string) *msgEventer {
	return &msgEventer{
		MsgReadWriter: rw,
		feed:          feed,
		peerID:        peerID,
		Protocol:      proto,
	}
}
165016
func NewMockServiceAccess(ctrl *gomock.Controller) *MockServiceAccess {
	mock := &MockServiceAccess{ctrl: ctrl}
	mock.recorder = &MockServiceAccessMockRecorder{mock}
	return mock
}
784423
func NewBucketService() *BucketService {
	return &BucketService{
		OpenFn:           func() error { return nil },
		CloseFn:          func() error { return nil },
		WithLoggerFn:     func(l *zap.Logger) {},
		FindBucketByIDFn: func(context.Context, platform.ID) (*platform.Bucket, error) { return nil, nil },
		FindBucketFn:     func(context.Context, platform.BucketFilter) (*platform.Bucket, error) { return nil, nil },
		FindBucketsFn: func(context.Context, platform.BucketFilter, ...platform.FindOptions) ([]*platform.Bucket, int, error) {
			return nil, 0, nil
		},
		CreateBucketFn: func(context.Context, *platform.Bucket) error { return nil },
		UpdateBucketFn: func(context.Context, platform.ID, platform.BucketUpdate) (*platform.Bucket, error) { return nil, nil },
		DeleteBucketFn: func(context.Context, platform.ID) error { return nil },
	}
}
1196274
func NewGCSHeader(r *http.Request) *GCSHeader {
	return &GCSHeader{
		ChannelID:     r.Header.Get("X-Goog-Channel-Id"),
		ClientToken:   r.Header.Get("X-Goog-Channel-Token"),
		ResourceID:    r.Header.Get("X-Goog-Resource-Id"),
		ResourceState: r.Header.Get("X-Goog-Resource-State"),
		ResourceURI:   r.Header.Get("X-Goog-Resource-Uri"),
	}
}
882445
func (p *peer) OnGossipBroadcast(src mesh.PeerName, buf []byte) (received mesh.GossipData, err error) {
	message, err := DecodeKVState(buf)
	if err != nil {
		glog.Warningf("error decoding OnGossipBroadcast: %v", err)
		return nil, err
	}

	deltas := &KVState{}
	p.st.merge(message, deltas)

	glog.V(4).Infof("OnGossipBroadcast %s %v => delta %v", src, message, deltas)

	return deltas, nil
}
290536
func NewCommInstance(s *grpc.Server, certs *common.TLSCertificates, idStore identity.Mapper,
	peerIdentity api.PeerIdentityType, secureDialOpts api.PeerSecureDialOpts, sa api.SecurityAdvisor,
	commMetrics *metrics.CommMetrics, config CommConfig, dialOpts ...grpc.DialOption) (Comm, error) {

	commInst := &commImpl{
		sa:             sa,
		pubSub:         util.NewPubSub(),
		PKIID:          idStore.GetPKIidOfCert(peerIdentity),
		idMapper:       idStore,
		logger:         util.GetLogger(util.CommLogger, ""),
		peerIdentity:   peerIdentity,
		opts:           dialOpts,
		secureDialOpts: secureDialOpts,
		msgPublisher:   NewChannelDemultiplexer(),
		lock:           &sync.Mutex{},
		deadEndpoints:  make(chan common.PKIidType, 100),
		stopping:       int32(0),
		exitChan:       make(chan struct{}),
		subscriptions:  make([]chan proto.ReceivedMessage, 0),
		tlsCerts:       certs,
		metrics:        commMetrics,
		dialTimeout:    config.DialTimeout,
		connTimeout:    config.ConnTimeout,
		recvBuffSize:   config.RecvBuffSize,
		sendBuffSize:   config.SendBuffSize,
	}

	connConfig := ConnConfig{
		RecvBuffSize: config.RecvBuffSize,
		SendBuffSize: config.SendBuffSize,
	}

	commInst.connStore = newConnStore(commInst, commInst.logger, connConfig)

	proto.RegisterGossipServer(s, commInst)

	return commInst, nil
}
197835
func NewIssueService(httpClient *http.Client) *IssueService {
	return &IssueService{
		sling: sling.New().Client(httpClient).Base(baseURL),
	}
}
1321316
func (a *ArgoCDRepoServer) CreateGRPC() *grpc.Server {
	server := grpc.NewServer(a.opts...)
	version.RegisterVersionServiceServer(server, &version.Server{})
	manifestService := repository.NewService(a.gitFactory, a.cache, a.parallelismLimit)
	repository.RegisterRepoServerServiceServer(server, manifestService)

	// Register reflection service on gRPC server.
	reflection.Register(server)

	return server
}
804564
func New(context fabcontext.Client, chConfig fab.ChannelCfg, discoveryService fab.DiscoveryService, opts ...options.Opt) (*Client, error) {
	params := defaultParams()
	options.Apply(params, opts)

	// Use a custom Discovery Service which wraps the given discovery service
	// and produces event endpoints containing additional GRPC options.
	discoveryWrapper, err := endpoint.NewEndpointDiscoveryWrapper(context, chConfig.ID(), discoveryService)
	if err != nil {
		return nil, err
	}

	dispatcher := dispatcher.New(context, chConfig, discoveryWrapper, params.connProvider, opts...)

	//default seek type is `Newest`
	if params.seekType == "" {
		params.seekType = seek.Newest
		//discard (do not publish) next BlockEvent/FilteredBlockEvent in dispatcher, since default seek type 'newest' is
		// only needed for block height calculations
		dispatcher.UpdateLastBlockInfoOnly()
	}

	client := &Client{
		Client: client.New(dispatcher, opts...),
		params: *params,
	}

	client.SetAfterConnectHandler(client.seek)
	client.SetBeforeReconnectHandler(client.setSeekFromLastBlockReceived)

	if err := client.Start(); err != nil {
		return nil, err
	}

	return client, nil
}
93465
func NewClusterService(id ServiceID, k8sService *Service, k8sEndpoints *Endpoints) service.ClusterService {
	svc := service.NewClusterService(id.Name, id.Namespace)

	for key, value := range k8sService.Labels {
		svc.Labels[key] = value
	}

	for key, value := range k8sService.Selector {
		svc.Selector[key] = value
	}

	portConfig := service.PortConfiguration{}
	for portName, port := range k8sService.Ports {
		portConfig[string(portName)] = port.L4Addr
	}

	svc.Frontends = map[string]service.PortConfiguration{}
	svc.Frontends[k8sService.FrontendIP.String()] = portConfig

	svc.Backends = map[string]service.PortConfiguration{}
	for ipString, portConfig := range k8sEndpoints.Backends {
		svc.Backends[ipString] = portConfig
	}

	return svc
}
103485
func NewMockOpener(ctrl *gomock.Controller) *MockOpener {
	mock := &MockOpener{ctrl: ctrl}
	mock.recorder = &MockOpenerMockRecorder{mock}
	return mock
}
844539
func (m *SyncManager) createGossipSyncer(peer lnpeer.Peer) *GossipSyncer {
	nodeID := route.Vertex(peer.PubKey())
	log.Infof("Creating new GossipSyncer for peer=%x", nodeID[:])

	encoding := lnwire.EncodingSortedPlain
	s := newGossipSyncer(gossipSyncerCfg{
		chainHash:     m.cfg.ChainHash,
		peerPub:       nodeID,
		channelSeries: m.cfg.ChanSeries,
		encodingType:  encoding,
		chunkSize:     encodingTypeToChunkSize[encoding],
		batchSize:     requestBatchSize,
		sendToPeer: func(msgs ...lnwire.Message) error {
			return peer.SendMessageLazy(false, msgs...)
		},
		sendToPeerSync: func(msgs ...lnwire.Message) error {
			return peer.SendMessageLazy(true, msgs...)
		},
	})

	// Gossip syncers are initialized by default in a PassiveSync type
	// and chansSynced state so that they can reply to any peer queries or
	// handle any sync transitions.
	s.setSyncState(chansSynced)
	s.setSyncType(PassiveSync)
	return s
}
535411
func NewLoggingService(logger log.Logger, s Service) Service {
	return &loggingService{logger, s}
}
1286157
func New(cfg Config, selfKey *btcec.PublicKey) *AuthenticatedGossiper {
	gossiper := &AuthenticatedGossiper{
		selfKey:                 selfKey,
		cfg:                     &cfg,
		networkMsgs:             make(chan *networkMsg),
		quit:                    make(chan struct{}),
		chanPolicyUpdates:       make(chan *chanPolicyUpdateRequest),
		prematureAnnouncements:  make(map[uint32][]*networkMsg),
		prematureChannelUpdates: make(map[uint64][]*networkMsg),
		channelMtx:              multimutex.NewMutex(),
		recentRejects:           make(map[uint64]struct{}),
		syncMgr: newSyncManager(&SyncManagerCfg{
			ChainHash:            cfg.ChainHash,
			ChanSeries:           cfg.ChanSeries,
			RotateTicker:         cfg.RotateTicker,
			HistoricalSyncTicker: cfg.HistoricalSyncTicker,
			NumActiveSyncers:     cfg.NumActiveSyncers,
		}),
	}

	gossiper.reliableSender = newReliableSender(&reliableSenderCfg{
		NotifyWhenOnline:  cfg.NotifyWhenOnline,
		NotifyWhenOffline: cfg.NotifyWhenOffline,
		MessageStore:      cfg.MessageStore,
		IsMsgStale:        gossiper.isMsgStale,
	})

	return gossiper
}