// NewPeer constructs a new peer
// this constructor is called by the p2p.Protocol#Run function
// the first two arguments are the arguments passed to p2p.Protocol.Run function
// the third argument is the Spec describing the protocol
967277
func NewPeer(p *p2p.Peer, rw p2p.MsgReadWriter, spec *Spec) *Peer {
	return &Peer{
		Peer: p,
		rw:   rw,
		spec: spec,
	}
}
804102
func (srv *Server) AddPeer(node *enode.Node) {
	select {
	case srv.addstatic <- node:
	case <-srv.quit:
	}
}
1162350
func newPeerContainer(geodb *geoDB) *peerContainer {
	return &peerContainer{
		Bundles:       make(map[string]*peerBundle),
		inactivePeers: list.New(),
		attemptOrder:  make([]string, 0, attemptLimit),
		geodb:         geodb,
	}
}
505100
func DiscoverPeers(n *Network, p *Peer, user, channelName string) func() []DiscoveredPeer {
	return func() []DiscoveredPeer {
		peers := commands.Peers{
			UserCert: n.PeerUserCert(p, user),
			UserKey:  n.PeerUserKey(p, user),
			MSPID:    n.Organization(p.Organization).MSPID,
			Server:   n.PeerAddress(p, ListenPort),
			Channel:  channelName,
		}
		sess, err := n.Discover(peers)
		Expect(err).NotTo(HaveOccurred())
		Eventually(sess).Should(gexec.Exit(0))

		var discovered []DiscoveredPeer
		err = json.Unmarshal(sess.Out.Contents(), &discovered)
		Expect(err).NotTo(HaveOccurred())
		return discovered
	}
}
998306
func New(ccp ccprovider.ChaincodeProvider, sccp sysccprovider.SystemChaincodeProvider, aclProvider aclmgmt.ACLProvider) *PeerConfiger {
	return &PeerConfiger{
		policyChecker: policy.NewPolicyChecker(
			peer.NewChannelPolicyManagerGetter(),
			mgmt.GetLocalMSP(),
			mgmt.NewLocalMSPPrincipalGetter(),
		),
		configMgr:   peer.NewConfigSupport(),
		ccp:         ccp,
		sccp:        sccp,
		aclProvider: aclProvider,
	}
}
577609
func newPeerConfig(sp *ServerPeer) *peer.Config {
	return &peer.Config{
		Listeners: peer.MessageListeners{
			OnVersion: sp.OnVersion,
			//OnVerAck:    sp.OnVerAck, // Don't use sendheaders yet
			OnInv:       sp.OnInv,
			OnHeaders:   sp.OnHeaders,
			OnReject:    sp.OnReject,
			OnFeeFilter: sp.OnFeeFilter,
			OnAddr:      sp.OnAddr,
			OnRead:      sp.OnRead,
			OnWrite:     sp.OnWrite,

			// Note: The reference client currently bans peers that send alerts
			// not signed with its key.  We could verify against their key, but
			// since the reference client is currently unwilling to support
			// other implementations' alert messages, we will not relay theirs.
			OnAlert: nil,
		},
		NewestBlock:      sp.newestBlock,
		HostToNetAddress: sp.server.addrManager.HostToNetAddress,
		UserAgentName:    sp.server.userAgentName,
		UserAgentVersion: sp.server.userAgentVersion,
		ChainParams:      &sp.server.chainParams,
		Services:         sp.server.services,
		ProtocolVersion:  wire.FeeFilterVersion,
		DisableRelayTx:   true,
	}
}
1263107
func (pn *peernet) ClosePeer(p peer.ID) error {
	pn.RLock()
	cs, found := pn.connsByPeer[p]
	if !found {
		pn.RUnlock()
		return nil
	}

	var conns []*conn
	for c := range cs {
		conns = append(conns, c)
	}
	pn.RUnlock()
	for _, c := range conns {
		c.Close()
	}
	return nil
}
365350
func New(transport peer.Transport, opts ...HeapOption) *List {
	cfg := defaultHeapConfig
	for _, o := range opts {
		o(&cfg)
	}

	return &List{
		once:               lifecycle.NewOnce(),
		transport:          transport,
		byIdentifier:       make(map[string]*peerScore),
		peerAvailableEvent: make(chan struct{}, 1),
		startupWait:        cfg.startupWait,
	}
}
373588
func newPeer(server *server, name string, connectionString string, heartbeatInterval time.Duration) *Peer {
	return &Peer{
		server:            server,
		Name:              name,
		ConnectionString:  connectionString,
		heartbeatInterval: heartbeatInterval,
	}
}
238494
func (sw *Switch) addPeer(p Peer) error {
	if err := sw.filterPeer(p); err != nil {
		return err
	}

	p.SetLogger(sw.Logger.With("peer", p.SocketAddr()))

	// Handle the shut down case where the switch has stopped but we're
	// concurrently trying to add a peer.
	if !sw.IsRunning() {
		// XXX should this return an error or just log and terminate?
		sw.Logger.Error("Won't start a peer - switch is not running", "peer", p)
		return nil
	}

	// Start the peer's send/recv routines.
	// Must start it before adding it to the peer set
	// to prevent Start and Stop from being called concurrently.
	err := p.Start()
	if err != nil {
		// Should never happen
		sw.Logger.Error("Error starting peer", "err", err, "peer", p)
		return err
	}

	// Add the peer to PeerSet. Do this before starting the reactors
	// so that if Receive errors, we will find the peer and remove it.
	// Add should not err since we already checked peers.Has().
	if err := sw.peers.Add(p); err != nil {
		return err
	}
	sw.metrics.Peers.Add(float64(1))

	// Start all the reactor protocols on the peer.
	for _, reactor := range sw.reactors {
		reactor.AddPeer(p)
	}

	sw.Logger.Info("Added peer", "peer", p)

	return nil
}
1326284
func New(config fab.EndpointConfig, opts ...Option) (*Peer, error) {
	peer := &Peer{
		config:      config,
		commManager: &defCommManager{},
	}

	for _, opt := range opts {
		err := opt(peer)

		if err != nil {
			return nil, err
		}
	}

	if peer.processor == nil {
		// TODO: config is declaring TLS but cert & serverHostOverride is being passed-in...
		endorseRequest := peerEndorserRequest{
			target:             peer.url,
			certificate:        peer.certificate,
			serverHostOverride: peer.serverName,
			config:             peer.config,
			kap:                peer.kap,
			failFast:           peer.failFast,
			allowInsecure:      peer.inSecure,
			commManager:        peer.commManager,
		}
		processor, err := newPeerEndorser(&endorseRequest)

		if err != nil {
			return nil, err
		}
		peer.processor = processor
	}

	return peer, nil
}
1028961
func (n *Network) PeerDir(p *Peer) string {
	return filepath.Join(n.RootDir, "peers", p.ID())
}
3929
func buildPeerListUpdater(c config.AttributeMap, identify func(string) peer.Identifier, kit *Kit) (peer.Binder, error) {
	// Special case for explicit list of peers.
	var peers []string
	if _, err := c.Pop("peers", &peers); err != nil {
		return nil, err
	}
	if len(peers) > 0 {
		return peerbind.BindPeers(identifyAll(identify, peers)), nil
	}
	// TODO: Make peers a separate peer list updater that is registered by
	// default instead of special casing here.

	var (
		// The peer list updater config is in the same namespace as the
		// attributes for the peer list config. We want to ensure that there is
		// exactly one peer list updater in the config.
		foundUpdaters []string

		// The peer list updater spec we'll actually use.
		peerListUpdaterSpec *compiledPeerListUpdaterSpec
	)

	for name := range c {
		spec := kit.peerListUpdaterSpec(name)
		if spec != nil {
			peerListUpdaterSpec = spec
			foundUpdaters = append(foundUpdaters, name)
		}
	}

	switch len(foundUpdaters) {
	case 0:
		return nil, fmt.Errorf(
			"no recognized peer list updater in config: got %s; need one of %s",
			strings.Join(configNames(c), ", "),
			strings.Join(kit.peerListUpdaterSpecNames(), ", "),
		)
	case 1:
		// fall through to logic below
	default:
		sort.Strings(foundUpdaters) // deterministic error message
		return nil, fmt.Errorf(
			"found too many peer list updaters in config: got %s",
			strings.Join(foundUpdaters, ", "))
	}

	var peerListUpdaterConfig config.AttributeMap
	if _, err := c.Pop(foundUpdaters[0], &peerListUpdaterConfig); err != nil {
		return nil, err
	}

	// This decodes all attributes on the peer list updater block, including the
	// field with the name of the peer list updater.
	peerListUpdaterBuilder, err := peerListUpdaterSpec.PeerListUpdater.Decode(peerListUpdaterConfig, config.InterpolateWith(kit.resolver))
	if err != nil {
		return nil, err
	}

	result, err := peerListUpdaterBuilder.Build(kit)
	if err != nil {
		return nil, err
	}

	return result.(peer.Binder), nil
}
466257
func (s *Store) AddPeer(peer string) error {
	err := s.raft.AddPeer(peer).Error()
	if err == raft.ErrNotLeader {
		err = ErrNotLeader
	} else if err == raft.ErrKnownPeer {
		return nil
	}
	return err
}
911805
func NewErr(constructorsAndValues ...interface{}) (*Psyringe, error) {
	p := newPsyringe()
	return p, p.addErr(constructorsAndValues...)
}
1045389
func NewEncrypter(kp *Keypair, peerPublic [32]byte) *Encrypter {
	var shared [32]byte
	box.Precompute(&shared, &peerPublic, &kp.Private)
	return &Encrypter{
		Keypair:    kp,
		PeerPublic: peerPublic,
		SharedKey:  shared,
	}
}
341014
func (pn *peernet) DialPeer(ctx context.Context, p peer.ID) (inet.Conn, error) {
	return pn.connect(p)
}