// Runs an emulated pss Protocol on the specified peer,
// linked to a specific topic
// `key` and `asymmetric` specifies what encryption key
// to link the peer to.
// The key must exist in the pss store prior to adding the peer.
518894
func (p *Protocol) AddPeer(peer *p2p.Peer, topic Topic, asymmetric bool, key string) (p2p.MsgReadWriter, error) {
	rw := &PssReadWriter{
		Pss:   p.Pss,
		rw:    make(chan p2p.Msg),
		spec:  p.spec,
		topic: p.topic,
		key:   key,
	}
	if asymmetric {
		rw.sendFunc = p.Pss.SendAsym
	} else {
		rw.sendFunc = p.Pss.SendSym
	}
	if asymmetric {
		if !p.Pss.isPubKeyStored(key) {
			return nil, fmt.Errorf("asym key does not exist: %s", key)
		}
		p.RWPoolMu.Lock()
		p.pubKeyRWPool[key] = rw
		p.RWPoolMu.Unlock()
	} else {
		if !p.Pss.isSymKeyStored(key) {
			return nil, fmt.Errorf("symkey does not exist: %s", key)
		}
		p.RWPoolMu.Lock()
		p.symKeyRWPool[key] = rw
		p.RWPoolMu.Unlock()
	}
	go func() {
		err := p.proto.Run(peer, rw)
		log.Warn(fmt.Sprintf("pss vprotocol quit on %v topic %v: %v", peer, topic, err))
	}()
	return rw, nil
}
1045604
func (c *EndpointConfig) peerMSPID(name string) (string, bool) {
	var mspID string
	// Find organisation/msp that peer belongs to
	for _, org := range c.networkConfig.Organizations {
		for i := 0; i < len(org.Peers); i++ {
			if strings.EqualFold(org.Peers[i], name) {
				// peer belongs to this org add org msp
				mspID = org.MSPID
				break
			} else {
				peer, ok := c.findMatchingPeer(org.Peers[i])
				if ok && strings.EqualFold(peer, name) {
					mspID = org.MSPID
					break
				}
			}
		}
	}

	return mspID, mspID != ""
}
958406
func (e *PGPVerify) Run(m libkb.MetaContext) error {
	var err error
	defer m.Trace("PGPVerify#Run", func() error { return err })()
	var sc libkb.StreamClassification
	sc, e.source, err = libkb.ClassifyStream(e.arg.Source)

	// For a Detached signature, we'll be expecting an UnknownStreamError
	if err != nil {
		if _, ok := err.(libkb.UnknownStreamError); !ok || len(e.arg.Signature) == 0 {
			return err
		}
	}

	if sc.Format == libkb.CryptoMessageFormatPGP && sc.Type == libkb.CryptoMessageTypeClearSignature {
		err = e.runClearsign(m)
		return err
	}
	if len(e.arg.Signature) == 0 {
		err = e.runAttached(m)
		return err
	}
	err = e.runDetached(m)
	return err
}
736926
func (p *Partition) Key() string {
	return fmt.Sprintf("%s/%d", p.topic.Name, p.ID)
}
329926
func Key(subseed Trits, securityLevel SecurityLevel, spongeFunc ...SpongeFunction) (Trits, error) {
	h := GetSpongeFunc(spongeFunc, kerl.NewKerl)
	defer h.Reset()

	keyLength := KeyFragmentLength * int(securityLevel)
	key := make(Trits, keyLength)

	err := h.Absorb(subseed)
	if err != nil {
		return nil, err
	}

	key, err = h.Squeeze(keyLength)
	if err != nil {
		return nil, err
	}

	h.Reset()

	for i := 0; i < KeyFragmentLength*int(securityLevel); i += HashTrinarySize {
		if err := h.Absorb(key[i : i+HashTrinarySize]); err != nil {
			return nil, err
		}

		buf, err := h.Squeeze(HashTrinarySize)
		if err != nil {
			return nil, err
		}
		copy(key[i:], buf)

		h.Reset()
	}

	return key, nil
}
16050
func RegisterProtocol(ps *Pss, topic *Topic, spec *protocols.Spec, targetprotocol *p2p.Protocol, options *ProtocolParams) (*Protocol, error) {
	if !options.Asymmetric && !options.Symmetric {
		return nil, fmt.Errorf("specify at least one of asymmetric or symmetric messaging mode")
	}
	pp := &Protocol{
		Pss:          ps,
		proto:        targetprotocol,
		topic:        topic,
		spec:         spec,
		pubKeyRWPool: make(map[string]p2p.MsgReadWriter),
		symKeyRWPool: make(map[string]p2p.MsgReadWriter),
		Asymmetric:   options.Asymmetric,
		Symmetric:    options.Symmetric,
	}
	return pp, nil
}
1336378
func (ks *KeyStore) SetPeerPublicKey(pubkey *ecdsa.PublicKey, topic Topic, address PssAddress) error {
	if err := validateAddress(address); err != nil {
		return err
	}
	pubkeybytes := crypto.FromECDSAPub(pubkey)
	if len(pubkeybytes) == 0 {
		return fmt.Errorf("invalid public key: %v", pubkey)
	}
	pubkeyid := common.ToHex(pubkeybytes)
	psp := &pssPeer{
		address: address,
	}
	ks.mx.Lock()
	if _, ok := ks.pubKeyPool[pubkeyid]; !ok {
		ks.pubKeyPool[pubkeyid] = make(map[Topic]*pssPeer)
	}
	ks.pubKeyPool[pubkeyid][topic] = psp
	ks.mx.Unlock()
	log.Trace("added pubkey", "pubkeyid", pubkeyid, "topic", topic, "address", address)
	return nil
}
962436
func (n *Network) PeerUserKey(p *Peer, user string) string {
	org := n.Organization(p.Organization)
	Expect(org).NotTo(BeNil())

	keystore := filepath.Join(
		n.PeerUserMSPDir(p, user),
		"keystore",
	)

	// file names are the SKI and non-deterministic
	keys, err := ioutil.ReadDir(keystore)
	Expect(err).NotTo(HaveOccurred())
	Expect(keys).To(HaveLen(1))

	return filepath.Join(keystore, keys[0].Name())
}
1355697
func (privKey PrivKeyEd25519) PubKey() crypto.PubKey {
	privKeyBytes := [64]byte(privKey)
	initialized := false
	// If the latter 32 bytes of the privkey are all zero, compute the pubkey
	// otherwise privkey is initialized and we can use the cached value inside
	// of the private key.
	for _, v := range privKeyBytes[32:] {
		if v != 0 {
			initialized = true
			break
		}
	}

	if !initialized {
		panic("Expected PrivKeyEd25519 to include concatenated pubkey bytes")
	}

	var pubkeyBytes [PubKeyEd25519Size]byte
	copy(pubkeyBytes[:], privKeyBytes[32:])
	return PubKeyEd25519(pubkeyBytes)
}
1210224
func (ks *KeyStore) GetSymmetricKey(symkeyid string) ([]byte, error) {
	return ks.w.GetSymKey(symkeyid)
}
1116562
func (msg *sentMessage) encryptAsymmetric(key *ecdsa.PublicKey) error {
	if !ValidatePublicKey(key) {
		return errors.New("invalid public key provided for asymmetric encryption")
	}
	encrypted, err := ecies.Encrypt(crand.Reader, ecies.ImportECDSAPublic(key), msg.Raw, nil, nil)
	if err == nil {
		msg.Raw = encrypted
	}
	return err
}
437540
func PublicKeyPinning(options PublicKeyPinningOptions) gear.Middleware {
	if len(options.Sha256s) == 0 {
		panic(gear.Err.WithMsg("empty Public-Key-Pins sha256s"))
	}

	return func(ctx *gear.Context) error {
		publicKeyPins := ""
		for _, sha256 := range options.Sha256s {
			publicKeyPins += fmt.Sprintf(`pin-sha256="%v";`, sha256)
		}
		if options.MaxAge != 0 {
			publicKeyPins += fmt.Sprintf("max-age=%.f;", options.MaxAge.Seconds())
		}
		if options.IncludeSubdomains {
			publicKeyPins += "includeSubDomains;"
		}
		if options.ReportURI != "" {
			publicKeyPins += fmt.Sprintf(`report-uri="%v"`, options.ReportURI)
		}

		if options.ReportOnly {
			ctx.SetHeader(gear.HeaderPublicKeyPinsReportOnly, publicKeyPins)
		} else {
			ctx.SetHeader(gear.HeaderPublicKeyPins, publicKeyPins)
		}
		return nil
	}
}
837989
func (ks *KeyStore) addSymmetricKeyToPool(keyid string, topic Topic, address PssAddress, addtocache bool, protected bool) {
	psp := &pssPeer{
		address:   address,
		protected: protected,
	}
	ks.mx.Lock()
	if _, ok := ks.symKeyPool[keyid]; !ok {
		ks.symKeyPool[keyid] = make(map[Topic]*pssPeer)
	}
	ks.symKeyPool[keyid][topic] = psp
	ks.mx.Unlock()
	if addtocache {
		ks.symKeyDecryptCacheCursor++
		ks.symKeyDecryptCache[ks.symKeyDecryptCacheCursor%cap(ks.symKeyDecryptCache)] = &keyid
	}
}
1145085
func (n *Node) Pubkey() *ecdsa.PublicKey {
	var key ecdsa.PublicKey
	if n.Load((*Secp256k1)(&key)) != nil {
		return nil
	}
	return &key
}
760859
func pubkeyFromPrivkey(privkey []byte, compress bool) (pubkey []byte) {
	_, pk := btcec.PrivKeyFromBytes(btcec.S256(), privkey)

	if compress {
		return pk.SerializeCompressed()
	}
	return pk.SerializeUncompressed()
}
715463
func (tms *TrustMetricStore) AddPeerTrustMetric(key string, tm *TrustMetric) {
	tms.mtx.Lock()
	defer tms.mtx.Unlock()

	if key == "" || tm == nil {
		return
	}
	tms.peerMetrics[key] = tm
}
641326
func (peer *Peer) handshake() error {
	// Send the handshake status message asynchronously
	errc := make(chan error, 1)
	isLightNode := peer.host.LightClientMode()
	isRestrictedLightNodeConnection := peer.host.LightClientModeConnectionRestricted()
	go func() {
		pow := peer.host.MinPow()
		powConverted := math.Float64bits(pow)
		bloom := peer.host.BloomFilter()

		errc <- p2p.SendItems(peer.ws, statusCode, ProtocolVersion, powConverted, bloom, isLightNode)
	}()

	// Fetch the remote status packet and verify protocol match
	packet, err := peer.ws.ReadMsg()
	if err != nil {
		return err
	}
	if packet.Code != statusCode {
		return fmt.Errorf("peer [%x] sent packet %x before status packet", peer.ID(), packet.Code)
	}
	s := rlp.NewStream(packet.Payload, uint64(packet.Size))
	_, err = s.List()
	if err != nil {
		return fmt.Errorf("peer [%x] sent bad status message: %v", peer.ID(), err)
	}
	peerVersion, err := s.Uint()
	if err != nil {
		return fmt.Errorf("peer [%x] sent bad status message (unable to decode version): %v", peer.ID(), err)
	}
	if peerVersion != ProtocolVersion {
		return fmt.Errorf("peer [%x]: protocol version mismatch %d != %d", peer.ID(), peerVersion, ProtocolVersion)
	}

	// only version is mandatory, subsequent parameters are optional
	powRaw, err := s.Uint()
	if err == nil {
		pow := math.Float64frombits(powRaw)
		if math.IsInf(pow, 0) || math.IsNaN(pow) || pow < 0.0 {
			return fmt.Errorf("peer [%x] sent bad status message: invalid pow", peer.ID())
		}
		peer.powRequirement = pow

		var bloom []byte
		err = s.Decode(&bloom)
		if err == nil {
			sz := len(bloom)
			if sz != BloomFilterSize && sz != 0 {
				return fmt.Errorf("peer [%x] sent bad status message: wrong bloom filter size %d", peer.ID(), sz)
			}
			peer.setBloomFilter(bloom)
		}
	}

	isRemotePeerLightNode, err := s.Bool()
	if isRemotePeerLightNode && isLightNode && isRestrictedLightNodeConnection {
		return fmt.Errorf("peer [%x] is useless: two light client communication restricted", peer.ID())
	}

	if err := <-errc; err != nil {
		return fmt.Errorf("peer [%x] failed to send status packet: %v", peer.ID(), err)
	}
	return nil
}