// rawPemBlock encodes a pem.Block to a slice of bytes.
428664
func rawPemBlock(block *pem.Block) ([]byte, error) {
	buffer := bytes.NewBuffer(nil)

	err := pem.Encode(buffer, block)
	if err != nil {
		return []byte{}, err
	}

	return buffer.Bytes(), nil
}
2460
func (m *Mutate) DeserializeCellBlocks(pm proto.Message, b []byte) (uint32, error) {
	resp := pm.(*pb.MutateResponse)
	if resp.Result == nil {
		// TODO: is this possible?
		return 0, nil
	}
	cells, read, err := deserializeCellBlocks(b, uint32(resp.Result.GetAssociatedCellCount()))
	if err != nil {
		return 0, err
	}
	resp.Result.Cell = append(resp.Result.Cell, cells...)
	return read, nil
}
957380
func ParsePEM(data, header string) ([]byte, error) {
	block, rest := pem.Decode([]byte(data))
	if len(rest) != 0 || block == nil {
		return nil, fmt.Errorf("not a valid %q PEM", header)
	}
	if block.Type != header {
		return nil, fmt.Errorf("expecting %q, got %q", header, block.Type)
	}
	return block.Bytes, nil
}
767201
func (a *btcAddress) lock() error {
	if !a.flags.encrypted {
		return errors.New("unable to lock unencrypted address")
	}

	zero(a.privKeyCT)
	a.privKeyCT = nil
	return nil
}
1036398
func FixupLockDelay(raw interface{}) error {
	rawMap, ok := raw.(map[string]interface{})
	if !ok {
		return nil
	}
	var key string
	for k := range rawMap {
		if strings.ToLower(k) == "lockdelay" {
			key = k
			break
		}
	}
	if key != "" {
		val := rawMap[key]
		// Convert a string value into an integer
		if vStr, ok := val.(string); ok {
			dur, err := time.ParseDuration(vStr)
			if err != nil {
				return err
			}
			if dur < lockDelayMinThreshold {
				dur = dur * time.Second
			}
			rawMap[key] = dur
		}
		// Convert low value integers into seconds
		if vNum, ok := val.(float64); ok {
			dur := time.Duration(vNum)
			if dur < lockDelayMinThreshold {
				dur = dur * time.Second
			}
			rawMap[key] = dur
		}
	}
	return nil
}
51420
func (util *RBDUtil) rbdUnlock(b rbdMounter) error {
	var err error
	var output, locker string
	var cmd []byte
	var secret_opt []string

	if b.Secret != "" {
		secret_opt = []string{"--key=" + b.Secret}
	} else {
		secret_opt = []string{"-k", b.Keyring}
	}
	if len(b.adminId) == 0 {
		b.adminId = b.Id
	}
	if len(b.adminSecret) == 0 {
		b.adminSecret = b.Secret
	}

	// Construct lock id using host name and a magic prefix.
	hostName, err := node.GetHostname("")
	if err != nil {
		return err
	}
	lock_id := kubeLockMagic + hostName

	mon := util.kernelRBDMonitorsOpt(b.Mon)

	// Get the locker name, something like "client.1234".
	args := []string{"lock", "list", b.Image, "--pool", b.Pool, "--id", b.Id, "-m", mon}
	args = append(args, secret_opt...)
	cmd, err = b.exec.Run("rbd", args...)
	output = string(cmd)
	klog.V(4).Infof("lock list output %q", output)
	if err != nil {
		return err
	}
	ind := strings.LastIndex(output, lock_id) - 1
	for i := ind; i >= 0; i-- {
		if output[i] == '\n' {
			locker = output[(i + 1):ind]
			break
		}
	}

	// Remove a lock if found: rbd lock remove.
	if len(locker) > 0 {
		args := []string{"lock", "remove", b.Image, lock_id, locker, "--pool", b.Pool, "--id", b.Id, "-m", mon}
		args = append(args, secret_opt...)
		cmd, err = b.exec.Run("rbd", args...)
		if err == nil {
			klog.V(4).Infof("rbd: successfully remove lock (locker_id: %s) on image: %s/%s with id %s mon %s", lock_id, b.Pool, b.Image, b.Id, mon)
		} else {
			klog.Warningf("rbd: failed to remove lock (lock_id: %s) on image: %s/%s with id %s mon %s: %v", lock_id, b.Pool, b.Image, b.Id, mon, err)
		}
	}

	return err
}
413088
func (bw *BlockWriter) commitBlock(encodedMetadataValue []byte) {
	// Set the orderer-related metadata field
	if encodedMetadataValue != nil {
		bw.lastBlock.Metadata.Metadata[cb.BlockMetadataIndex_ORDERER] = utils.MarshalOrPanic(&cb.Metadata{Value: encodedMetadataValue})
	}

	bw.addLastConfigSignature(bw.lastBlock)
	bw.addBlockSignature(bw.lastBlock)

	err := bw.support.Append(bw.lastBlock)
	if err != nil {
		logger.Panicf("[channel: %s] Could not append block: %s", bw.support.ChainID(), err)
	}
	logger.Debugf("[channel: %s] Wrote block [%d]", bw.support.ChainID(), bw.lastBlock.GetHeader().Number)
}
1314042
func (p *BlockPuller) PullBlock(seq uint64) *common.Block {
	retriesLeft := p.MaxPullBlockRetries
	for {
		block := p.tryFetchBlock(seq)
		if block != nil {
			return block
		}
		retriesLeft--
		if retriesLeft == 0 && p.MaxPullBlockRetries > 0 {
			p.Logger.Errorf("Failed pulling block [%d]: retry count exhausted(%d)", seq, p.MaxPullBlockRetries)
			return nil
		}
		time.Sleep(p.RetryTimeout)
	}
}
579033
func (bc *BlockChanges) AddRefBlock(ptr data.BlockPointer) {
	if bc.sizeEstimate != 0 {
		panic("Can't alter block changes after the size is estimated")
	}
	bc.Ops[len(bc.Ops)-1].AddRefBlock(ptr)
}
777689
func (s Store) DecodeBlock(block *pem.Block) error {
	switch BlockType(block.Type) {
	case PrivateKey:
		// try pkcs1 and then pkcs8 decoding
		key, err := ParsePKCSPrivateKey(block.Bytes)
		if err == nil {
			return s.add(RSAPrivateKey, key)
		}

		// must be a raw key (ie, use decoded b64 value as key)
		return s.add(PrivateKey, block.Bytes)

	case PublicKey:
		key, err := x509.ParsePKIXPublicKey(block.Bytes)
		if err != nil {
			// use the raw b64 decoded bytes
			key = block.Bytes
		}
		return s.add(PublicKey, key)

	case RSAPrivateKey:
		// try pkcs1 then pkcs8 decoding
		key, err := ParsePKCSPrivateKey(block.Bytes)
		if err != nil {
			return err
		}
		return s.add(RSAPrivateKey, key)

	case ECPrivateKey:
		key, err := x509.ParseECPrivateKey(block.Bytes)
		if err != nil {
			return err
		}
		return s.add(ECPrivateKey, key)

	case Certificate:
		cert, err := x509.ParseCertificate(block.Bytes)
		if err != nil {
			return err
		}
		return s.add(Certificate, cert)
	}

	return fmt.Errorf("unknown block type %s", block.Type)
}
297804
func (l *FileLock) SharedLock() error {
	return syscall.Flock(l.fd, syscall.LOCK_SH)
}
1113334
func EncryptPEMBlock(data, password []byte) (*pem.Block, error) {
	encryptedBytes, err := encryptPrivateKey(data, password)
	if err != nil {
		return nil, err
	}

	return &pem.Block{
		Type:    "ENCRYPTED PRIVATE KEY",
		Headers: map[string]string{},
		Bytes:   encryptedBytes,
	}, nil
}
1314360
func (m UnblockingMutex) TryLock() (result bool) {
	select {
	case m.C <- true:
		return true
	default:
		return false
	}
}
1068290
func (d *DeliverClient) GetSpecifiedBlock(num uint64) (*cb.Block, error) {
	err := d.seekSpecified(num)
	if err != nil {
		return nil, errors.WithMessage(err, "error getting specified block")
	}

	return d.readBlock()
}
448485
func BlockPullerFromConfigBlock(conf PullerConfig, block *common.Block, verifierRetriever VerifierRetriever) (*BlockPuller, error) {
	if block == nil {
		return nil, errors.New("nil block")
	}

	endpointconfig, err := EndpointconfigFromConfigBlock(block)
	if err != nil {
		return nil, err
	}

	dialer := &StandardDialer{
		Dialer: NewTLSPinningDialer(comm.ClientConfig{
			Timeout: conf.Timeout,
			SecOpts: &comm.SecureOptions{
				ServerRootCAs:     endpointconfig.TLSRootCAs,
				Certificate:       conf.TLSCert,
				Key:               conf.TLSKey,
				RequireClientCert: true,
				UseTLS:            true,
			},
		})}

	tlsCertAsDER, _ := pem.Decode(conf.TLSCert)
	if tlsCertAsDER == nil {
		return nil, errors.Errorf("unable to decode TLS certificate PEM: %s", base64.StdEncoding.EncodeToString(conf.TLSCert))
	}

	return &BlockPuller{
		Logger:  flogging.MustGetLogger("orderer.common.cluster.replication"),
		Dialer:  dialer,
		TLSCert: tlsCertAsDER.Bytes,
		VerifyBlockSequence: func(blocks []*common.Block, channel string) error {
			verifier := verifierRetriever.RetrieveVerifier(channel)
			if verifier == nil {
				return errors.Errorf("couldn't acquire verifier for channel %s", channel)
			}
			return VerifyBlocks(blocks, verifier)
		},
		MaxTotalBufferBytes: conf.MaxTotalBufferBytes,
		Endpoints:           endpointconfig.Endpoints,
		RetryTimeout:        RetryTimeout,
		FetchTimeout:        conf.Timeout,
		Channel:             conf.Channel,
		Signer:              conf.Signer,
	}, nil
}
1336985
func (c *Certificate) MarshalPEM() (pem_block []byte, err error) {
	bio := C.BIO_new(C.BIO_s_mem())
	if bio == nil {
		return nil, errors.New("failed to allocate memory BIO")
	}
	defer C.BIO_free(bio)
	if int(C.PEM_write_bio_X509(bio, c.x)) != 1 {
		return nil, errors.New("failed dumping certificate")
	}
	return ioutil.ReadAll(asAnyBio(bio))
}
615624
func (rw LeveledRWMutex) RLock(lockState *LockState) {
	err := lockState.doLock(rw.level, readExclusion, rw.rwLocker.RLocker())
	if err != nil {
		panic(err)
	}
}