// PackRetransmission packs a retransmission
// For packets sent after completion of the handshake, it might happen that 2 packets have to be sent.
// This can happen e.g. when a longer packet number is used in the header.
348560
func (p *packetPacker) PackRetransmission(packet *ackhandler.Packet) ([]*packedPacket, error) {
	var controlFrames []wire.Frame
	var streamFrames []*wire.StreamFrame
	for _, f := range packet.Frames {
		// CRYPTO frames are treated as control frames here.
		// Since we're making sure that the header can never be larger for a retransmission,
		// we never have to split CRYPTO frames.
		if sf, ok := f.(*wire.StreamFrame); ok {
			sf.DataLenPresent = true
			streamFrames = append(streamFrames, sf)
		} else {
			controlFrames = append(controlFrames, f)
		}
	}

	var packets []*packedPacket
	encLevel := packet.EncryptionLevel
	sealer, err := p.cryptoSetup.GetSealerWithEncryptionLevel(encLevel)
	if err != nil {
		return nil, err
	}
	for len(controlFrames) > 0 || len(streamFrames) > 0 {
		var frames []wire.Frame
		var length protocol.ByteCount

		header := p.getHeader(encLevel)
		headerLen := header.GetLength(p.version)
		maxSize := p.maxPacketSize - protocol.ByteCount(sealer.Overhead()) - headerLen

		for len(controlFrames) > 0 {
			frame := controlFrames[0]
			frameLen := frame.Length(p.version)
			if length+frameLen > maxSize {
				break
			}
			length += frameLen
			frames = append(frames, frame)
			controlFrames = controlFrames[1:]
		}

		for len(streamFrames) > 0 && length+protocol.MinStreamFrameSize < maxSize {
			frame := streamFrames[0]
			frame.DataLenPresent = false
			frameToAdd := frame

			sf, err := frame.MaybeSplitOffFrame(maxSize-length, p.version)
			if err != nil {
				return nil, err
			}
			if sf != nil {
				frameToAdd = sf
			} else {
				streamFrames = streamFrames[1:]
			}
			frame.DataLenPresent = true
			length += frameToAdd.Length(p.version)
			frames = append(frames, frameToAdd)
		}
		if sf, ok := frames[len(frames)-1].(*wire.StreamFrame); ok {
			sf.DataLenPresent = false
		}
		p, err := p.writeAndSealPacket(header, payload{frames: frames, length: length}, encLevel, sealer)
		if err != nil {
			return nil, err
		}
		packets = append(packets, p)
	}
	return packets, nil
}
924136
func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx hexutil.Bytes) (common.Hash, error) {
	tx := new(types.Transaction)
	if err := rlp.DecodeBytes(encodedTx, tx); err != nil {
		return common.Hash{}, err
	}
	return SubmitTransaction(ctx, s.b, tx)
}
676087
func (r *Route) WritePacket(gso *GSO, hdr buffer.Prependable, payload buffer.VectorisedView, protocol tcpip.TransportProtocolNumber, ttl uint8) *tcpip.Error {
	err := r.ref.ep.WritePacket(r, gso, hdr, payload, protocol, ttl, r.loop)
	if err != nil {
		r.Stats().IP.OutgoingPacketErrors.Increment()
	} else {
		r.ref.nic.stats.Tx.Packets.Increment()
		r.ref.nic.stats.Tx.Bytes.IncrementBy(uint64(hdr.UsedLength() + payload.Size()))
	}
	return err
}
115155
func newTransfer(tr *Transfer, name string, path string) *Transfer {
	t := &Transfer{
		Name:          name,
		Path:          path,
		Oid:           tr.Oid,
		Size:          tr.Size,
		Authenticated: tr.Authenticated,
		Actions:       make(ActionSet),
	}

	if tr.Error != nil {
		t.Error = &ObjectError{
			Code:    tr.Error.Code,
			Message: tr.Error.Message,
		}
	}

	for rel, action := range tr.Actions {
		t.Actions[rel] = &Action{
			Href:      action.Href,
			Header:    action.Header,
			ExpiresAt: action.ExpiresAt,
			ExpiresIn: action.ExpiresIn,
			createdAt: action.createdAt,
		}
	}

	if tr.Links != nil {
		t.Links = make(ActionSet)

		for rel, link := range tr.Links {
			t.Links[rel] = &Action{
				Href:      link.Href,
				Header:    link.Header,
				ExpiresAt: link.ExpiresAt,
				ExpiresIn: link.ExpiresIn,
				createdAt: link.createdAt,
			}
		}
	}

	return t
}
571300
func MaxPacketNumber(a, b protocol.PacketNumber) protocol.PacketNumber {
	if a > b {
		return a
	}
	return b
}
95572
func retransmitLimit(retransmitMult, n int) int {
	nodeScale := math.Ceil(math.Log10(float64(n + 1)))
	limit := retransmitMult * int(nodeScale)
	return limit
}
577580
func (c *MConnection) sendPacketMsg() bool {
	// Choose a channel to create a PacketMsg from.
	// The chosen channel will be the one whose recentlySent/priority is the least.
	var leastRatio float32 = math.MaxFloat32
	var leastChannel *Channel
	for _, channel := range c.channels {
		// If nothing to send, skip this channel
		if !channel.isSendPending() {
			continue
		}
		// Get ratio, and keep track of lowest ratio.
		ratio := float32(channel.recentlySent) / float32(channel.desc.Priority)
		if ratio < leastRatio {
			leastRatio = ratio
			leastChannel = channel
		}
	}

	// Nothing to send?
	if leastChannel == nil {
		return true
	}
	// c.Logger.Info("Found a msgPacket to send")

	// Make & send a PacketMsg from this channel
	_n, err := leastChannel.writePacketMsgTo(c.bufConnWriter)
	if err != nil {
		c.Logger.Error("Failed to write PacketMsg", "err", err)
		c.stopForError(err)
		return true
	}
	c.sendMonitor.Update(int(_n))
	c.flushTimer.Set()
	return false
}
54034
func (m *EncapsulatedData) Pack() []byte {
	data := new(bytes.Buffer)
	binary.Write(data, binary.LittleEndian, m.SEQNR)
	binary.Write(data, binary.LittleEndian, m.DATA)
	return data.Bytes()
}
1335775
func (rpc *EthRPC) EthSendRawTransaction(data string) (string, error) {
	var hash string

	err := rpc.call("eth_sendRawTransaction", &hash, data)
	return hash, err
}
95440
func (c *Client) RenewalRequestPacket(acknowledgement *dhcp4.Packet) dhcp4.Packet {
	messageid := make([]byte, 4)
	c.generateXID(messageid)

	acknowledgementOptions := acknowledgement.ParseOptions()

	packet := dhcp4.NewPacket(dhcp4.BootRequest)
	packet.SetCHAddr(acknowledgement.CHAddr())

	packet.SetXId(messageid)
	packet.SetCIAddr(acknowledgement.YIAddr())
	packet.SetSIAddr(acknowledgement.SIAddr())

	packet.SetBroadcast(c.broadcast)
	packet.AddOption(dhcp4.OptionDHCPMessageType, []byte{byte(dhcp4.Request)})
	packet.AddOption(dhcp4.OptionRequestedIPAddress, (acknowledgement.YIAddr()).To4())
	packet.AddOption(dhcp4.OptionServerIdentifier, acknowledgementOptions[dhcp4.OptionServerIdentifier])

	return packet
}
575472
func (t *Tx) CompletedPacket() (id uint64, ok bool) {
	for {
		b := t.rx.Pull()
		if b == nil {
			return 0, false
		}

		if len(b) != 8 {
			t.rx.Flush()
			log.Printf("Ignoring completed packet: size (%v) is less than expected (%v)", len(b), 8)
			continue
		}

		v := binary.LittleEndian.Uint64(b)

		t.rx.Flush()

		return v, true
	}
}
685524
func (t *TcpTransport) SendRecv(message *proto.Msg) (*proto.Msg, error) {
	response_ch := make(chan response)
	t.requestQueue <- request{message, response_ch}
	r := <-response_ch
	return r.message, r.err
}
317343
func sendPacket(w io.Writer, m encoding.BinaryMarshaler) error {
	bb, err := m.MarshalBinary()
	if err != nil {
		return errors.Errorf("binary marshaller failed: %v", err)
	}
	if debugDumpTxPacketBytes {
		debug("send packet: %s %d bytes %x", fxp(bb[0]), len(bb), bb[1:])
	} else if debugDumpTxPacket {
		debug("send packet: %s %d bytes", fxp(bb[0]), len(bb))
	}
	// Slide packet down 4 bytes to make room for length header.
	packet := append(bb, make([]byte, 4)...) // optimistically assume bb has capacity
	copy(packet[4:], bb)
	binary.BigEndian.PutUint32(packet[:4], uint32(len(bb)))

	_, err = w.Write(packet)
	if err != nil {
		return errors.Errorf("failed to send packet: %v", err)
	}
	return nil
}
1032148
func PackRremove(fc *Fcall) error {
	_, err := packCommon(fc, 0, Rremove)
	return err
}
1189551
func (s *Sender) SendWithRetries(msg *Message, to string, retries int) (result *Result, err error) {
	if err := checkUnrecoverableErrors(s, to, nil, msg, retries); err != nil {
		return nil, err
	}
	attempt, backoff := 0, BackoffInitialDelay
	for {
		attempt++
		result, err = s.SendNoRetry(msg, to)
		// NOTE: partial success for a device group message is considered successful

		tryAgain := false
		if attempt <= retries {
			if result != nil && (result.Error == ErrorUnavailable || result.Error == ErrorInternalServerError) {
				tryAgain = true
			} else if err != nil {
				if httpErr, isHTTPErr := err.(httpError); isHTTPErr {
					tryAgain = httpErr.statusCode >= http.StatusInternalServerError && httpErr.statusCode < 600
				}
			}
		}

		if tryAgain {
			sleepTime := backoff/2 + rand.Intn(backoff)
			time.Sleep(time.Duration(sleepTime) * time.Millisecond)
			backoff = min(2*backoff, MaxBackoffDelay)
		} else {
			break
		}
	}
	return
}
321502
func (c *Conn) receivePacket(h header, payload []byte) {
	c.packetReadTimeoutTimer.Reset(packetReadTimeout)
	c.processDelivery(h, payload)
}
359884
func (m *HighresImu) Pack() []byte {
	data := new(bytes.Buffer)
	binary.Write(data, binary.LittleEndian, m.TIME_USEC)
	binary.Write(data, binary.LittleEndian, m.XACC)
	binary.Write(data, binary.LittleEndian, m.YACC)
	binary.Write(data, binary.LittleEndian, m.ZACC)
	binary.Write(data, binary.LittleEndian, m.XGYRO)
	binary.Write(data, binary.LittleEndian, m.YGYRO)
	binary.Write(data, binary.LittleEndian, m.ZGYRO)
	binary.Write(data, binary.LittleEndian, m.XMAG)
	binary.Write(data, binary.LittleEndian, m.YMAG)
	binary.Write(data, binary.LittleEndian, m.ZMAG)
	binary.Write(data, binary.LittleEndian, m.ABS_PRESSURE)
	binary.Write(data, binary.LittleEndian, m.DIFF_PRESSURE)
	binary.Write(data, binary.LittleEndian, m.PRESSURE_ALT)
	binary.Write(data, binary.LittleEndian, m.TEMPERATURE)
	binary.Write(data, binary.LittleEndian, m.FIELDS_UPDATED)
	return data.Bytes()
}