// FetchEnvelope returns a message's envelope from its header.
555384
func FetchEnvelope(h message.Header) (*imap.Envelope, error) {
	mh := mail.Header{Header: h}

	env := new(imap.Envelope)
	env.Date, _ = mh.Date()
	env.Subject, _ = mh.Subject()
	env.From, _ = headerAddressList(mh, "From")
	env.Sender, _ = headerAddressList(mh, "Sender")
	env.ReplyTo, _ = headerAddressList(mh, "Reply-To")
	env.To, _ = headerAddressList(mh, "To")
	env.Cc, _ = headerAddressList(mh, "Cc")
	env.Bcc, _ = headerAddressList(mh, "Bcc")
	env.InReplyTo = mh.Get("In-Reply-To")
	env.MessageId = mh.Get("Message-Id")

	return env, nil
}
293417
func (c *connection) Fetch(req *proto.FetchReq) (*proto.FetchResp, error) {
	b, err := c.sendRequest(req)
	if err != nil {
		return nil, err
	}

	resp, err := proto.ReadVersionedFetchResp(bytes.NewReader(b), req.GetVersion())
	if err != nil {
		return nil, err
	}

	// Compressed messages are returned in full batches for efficiency
	// (the broker doesn't need to decompress).
	// This means that it's possible to get some leading messages
	// with a smaller offset than requested. Trim those.
	for ti := range resp.Topics {
		topic := &resp.Topics[ti]
		reqTopic := &req.Topics[ti]
		for pi := range topic.Partitions {
			partition := &topic.Partitions[pi]
			requestedOffset := reqTopic.Partitions[pi].FetchOffset
			i := 0
			if partition.MessageVersion < 2 {
				for _, msg := range partition.Messages {
					if msg.Offset >= requestedOffset {
						break
					}
					i++
				}
				partition.Messages = partition.Messages[i:]
			} else {
				firstOffset := partition.RecordBatch.FirstOffset
				for _, rec := range partition.RecordBatch.Records {
					if firstOffset+rec.OffsetDelta >= requestedOffset {
						break
					}
					i++
				}
				partition.RecordBatch.Records = partition.RecordBatch.Records[i:]
			}
		}
	}
	return resp, nil
}
363740
func (e *Envelope) rlpWithoutNonce() []byte {
	res, _ := rlp.EncodeToBytes([]interface{}{e.Expiry, e.TTL, e.Topic, e.Data})
	return res
}
266947
func (c *consumer) fetch() ([]*proto.Message, error) {
	req := proto.FetchReq{
		RequestHeader: proto.RequestHeader{ClientID: c.broker.conf.ClientID},
		MaxWaitTime:   c.conf.RequestTimeout,
		MinBytes:      c.conf.MinFetchSize,
		Topics: []proto.FetchReqTopic{
			{
				Name: c.conf.Topic,
				Partitions: []proto.FetchReqPartition{
					{
						ID:          c.conf.Partition,
						FetchOffset: c.offset,
						MaxBytes:    c.conf.MaxFetchSize,
					},
				},
			},
		},
	}

	var resErr error
consumeRetryLoop:
	for retry := 0; retry < c.conf.RetryErrLimit; retry++ {
		if retry != 0 {
			time.Sleep(c.conf.RetryErrWait)
		}

		if c.conn == nil {
			conn, err := c.broker.muLeaderConnection(c.conf.Topic, c.conf.Partition)
			if err != nil {
				resErr = err
				continue
			}
			c.conn = conn
		}

		resp, err := c.conn.Fetch(&req)
		resErr = err

		if _, ok := err.(*net.OpError); ok || err == io.EOF || err == syscall.EPIPE {
			c.conf.Logger.Debug("connection died while fetching message",
				"topic", c.conf.Topic,
				"partition", c.conf.Partition,
				"error", err)
			c.broker.muCloseDeadConnection(c.conn)
			c.conn = nil
			continue
		}

		if err != nil {
			c.conf.Logger.Debug("cannot fetch messages: unknown error",
				"retry", retry,
				"error", err)
			c.broker.muCloseDeadConnection(c.conn)
			c.conn = nil
			continue
		}

		for _, topic := range resp.Topics {
			if topic.Name != c.conf.Topic {
				c.conf.Logger.Warn("unexpected topic information received",
					"got", topic.Name,
					"expected", c.conf.Topic)
				continue
			}
			for _, part := range topic.Partitions {
				if part.ID != c.conf.Partition {
					c.conf.Logger.Warn("unexpected partition information received",
						"topic", topic.Name,
						"expected", c.conf.Partition,
						"got", part.ID)
					continue
				}
				switch part.Err {
				case proto.ErrLeaderNotAvailable,
					proto.ErrNotLeaderForPartition,
					proto.ErrBrokerNotAvailable,
					proto.ErrUnknownTopicOrPartition:

					c.conf.Logger.Debug("cannot fetch messages",
						"retry", retry,
						"error", part.Err)
					if err := c.broker.muRefreshMetadata(); err != nil {
						c.conf.Logger.Debug("cannot refresh metadata",
							"error", err)
					}
					// The connection is fine, so don't close it,
					// but we may very well need to talk to a different broker now.
					// Set the conn to nil so that next time around the loop
					// we'll check the metadata again to see who we're supposed to talk to.
					c.conn = nil
					continue consumeRetryLoop
				}
				if part.MessageVersion < 2 {
					return part.Messages, part.Err
				} else {
					// In the kafka > 0.11 MessageSet was replaced
					// with a new structure called RecordBatch
					// and Message was replaced with Record
					// In order to keep API for Consumer
					// here we repack Records to Messages

					messages := make([]*proto.Message, 0, len(part.RecordBatch.Records))
					for _, r := range part.RecordBatch.Records {
						m := &proto.Message{
							Key:       r.Key,
							Value:     r.Value,
							Offset:    part.RecordBatch.FirstOffset + r.OffsetDelta,
							Topic:     topic.Name,
							Partition: part.ID,
							TipOffset: part.TipOffset,
						}
						messages = append(messages, m)
					}

					return messages, part.Err
				}
			}
		}
		return nil, errors.New("incomplete fetch response")
	}

	return nil, resErr
}
612235
func ExtractPayload(envelope *cb.Envelope) (*cb.Payload, error) {
	payload := &cb.Payload{}
	err := proto.Unmarshal(envelope.Payload, payload)
	err = errors.Wrap(err, "no payload in envelope")
	return payload, err
}
1339474
func payloadLenForMsgLen(messageLength int) int {
	headerLength := len(recordsHeader)
	payloadLength := messageLength - 4 - 4 - 4 - headerLength - 4
	return payloadLength
}
1155927
func (e *ExchangeMessage) ClearHeader() {
	keys := e.head.ListKeys()
	for _, k := range keys {
		e.head.Del(k)
	}
}
317509
func CreateConfigEnvelope(data []byte) (*common.ConfigEnvelope, error) {

	envelope := &common.Envelope{}
	if err := proto.Unmarshal(data, envelope); err != nil {
		return nil, errors.Wrap(err, "unmarshal envelope from config block failed")
	}
	payload := &common.Payload{}
	if err := proto.Unmarshal(envelope.Payload, payload); err != nil {
		return nil, errors.Wrap(err, "unmarshal payload from envelope failed")
	}
	channelHeader := &common.ChannelHeader{}
	if err := proto.Unmarshal(payload.Header.ChannelHeader, channelHeader); err != nil {
		return nil, errors.Wrap(err, "unmarshal payload from envelope failed")
	}
	if common.HeaderType(channelHeader.Type) != common.HeaderType_CONFIG {
		return nil, errors.New("block must be of type 'CONFIG'")
	}
	configEnvelope := &common.ConfigEnvelope{}
	if err := proto.Unmarshal(payload.Data, configEnvelope); err != nil {
		return nil, errors.Wrap(err, "unmarshal config envelope failed")
	}

	return configEnvelope, nil
}
216323
func fetchViaSerialPort(key string) ([]byte, error) {
	config := &serial.Config{Name: SerialPort, Baud: Baud}
	connection, err := serial.OpenPort(config)
	if err != nil {
		return nil, err
	}

	query := fmt.Sprintf(requestPattern, key)
	if _, err := connection.Write([]byte(query)); err != nil {
		return nil, err
	}

	reader := bufio.NewReader(connection)
	answer, err := reader.ReadBytes(EOT)
	if err != nil {
		return nil, err
	}

	return answer[0 : len(answer)-1], nil
}
743364
func SendEnvelope(envelope *events.Envelope) error {
	if envelopeSender == nil {
		return nil
	}
	return envelopeSender.SendEnvelope(envelope)
}
1038109
func (v Envelope) MarshalJSON() ([]byte, error) {
	w := jwriter.Writer{}
	easyjsonCce3d1beEncodeGithubComMailgunMailgunGoEvents6(&w, v)
	return w.Buffer.BuildBytes(), w.Error
}
1080350
func (h *blockHeaderStore) FetchHeaderByHeight(height uint32) (*wire.BlockHeader, error) {
	// Lock store for read.
	h.mtx.RLock()
	defer h.mtx.RUnlock()

	// For this query, we don't need to consult the index, and can instead
	// just seek into the flat file based on the target height and return
	// the full header.
	header, err := h.readHeader(height)
	if err != nil {
		return nil, err
	}

	return &header, nil
}
299314
func fetchParam(param string, c *Conn, m mailstore.Message) (string, error) {
	peek := false
	if peekRE.MatchString(param) {
		peek = true
	}
	// Search through the parameter list until a parameter handler is found
	for _, element := range registeredFetchParams {
		if element.re.MatchString(param) {
			return element.handler(element.re.FindStringSubmatch(param), c, m, peek), nil
		}
	}
	return "", ErrUnrecognisedParameter
}
849342
func (e *ExchangeMessage) GetHeader(k string) string {
	return e.head.Get(k)
}
1043204
func FetchBodyStructure(e *message.Entity, extended bool) (*imap.BodyStructure, error) {
	bs := new(imap.BodyStructure)

	mediaType, mediaParams, _ := e.Header.ContentType()
	typeParts := strings.SplitN(mediaType, "/", 2)
	bs.MIMEType = typeParts[0]
	if len(typeParts) == 2 {
		bs.MIMESubType = typeParts[1]
	}
	bs.Params = mediaParams

	bs.Id = e.Header.Get("Content-Id")
	bs.Description = e.Header.Get("Content-Description")
	bs.Encoding = e.Header.Get("Content-Encoding")
	// TODO: bs.Size

	if mr := e.MultipartReader(); mr != nil {
		var parts []*imap.BodyStructure
		for {
			p, err := mr.NextPart()
			if err == io.EOF {
				break
			} else if err != nil {
				return nil, err
			}

			pbs, err := FetchBodyStructure(p, extended)
			if err != nil {
				return nil, err
			}
			parts = append(parts, pbs)
		}
		bs.Parts = parts
	}

	// TODO: bs.Envelope, bs.BodyStructure
	// TODO: bs.Lines

	if extended {
		bs.Extended = true

		bs.Disposition, bs.DispositionParams, _ = e.Header.ContentDisposition()

		// TODO: bs.Language, bs.Location
		// TODO: bs.MD5
	}

	return bs, nil
}
1199758
func (d *Downloader) fetchHeight(p *peerConnection) (*types.Header, error) {
	p.log.Debug("Retrieving remote chain height")

	// Request the advertised remote head block and wait for the response
	head, _ := p.peer.Head()
	go p.peer.RequestHeadersByHash(head, 1, 0, false)

	ttl := d.requestTTL()
	timeout := time.After(ttl)
	for {
		select {
		case <-d.cancelCh:
			return nil, errCancelBlockFetch

		case packet := <-d.headerCh:
			// Discard anything not from the origin peer
			if packet.PeerId() != p.id {
				log.Debug("Received headers from incorrect peer", "peer", packet.PeerId())
				break
			}
			// Make sure the peer actually gave something valid
			headers := packet.(*headerPack).headers
			if len(headers) != 1 {
				p.log.Debug("Multiple headers for single request", "headers", len(headers))
				return nil, errBadPeer
			}
			head := headers[0]
			if (d.mode == FastSync || d.mode == LightSync) && head.Number.Uint64() < d.checkpoint {
				p.log.Warn("Remote head below checkpoint", "number", head.Number, "hash", head.Hash())
				return nil, errUnsyncedPeer
			}
			p.log.Debug("Remote head header identified", "number", head.Number, "hash", head.Hash())
			return head, nil

		case <-timeout:
			p.log.Debug("Waiting for head header timed out", "elapsed", ttl)
			return nil, errTimeout

		case <-d.bodyCh:
		case <-d.receiptCh:
			// Out of bounds delivery, ignore
		}
	}
}
561398
func ExtractEnvelope(block *cb.Block, index int) (*cb.Envelope, error) {
	if block.Data == nil {
		return nil, errors.New("block data is nil")
	}

	envelopeCount := len(block.Data.Data)
	if index < 0 || index >= envelopeCount {
		return nil, errors.New("envelope index out of bounds")
	}
	marshaledEnvelope := block.Data.Data[index]
	envelope, err := GetEnvelopeFromBlock(marshaledEnvelope)
	err = errors.WithMessage(err, fmt.Sprintf("block data does not carry an envelope at index %d", index))
	return envelope, err
}