receiveLoop

suspend fun receiveLoop(maxMessageLength: Int = DEFAULT_MAX_MESSAGE_LENGTH, onMessage: suspend (PeerMessage) -> Unit)

Read and dispatch peer-wire messages until the stream closes (or the coroutine is cancelled). Ports the post-handshake framing of on_receive: read the 4-byte big-endian length prefix, then the body, then decode and dispatch. This is the suspending equivalent of libtorrent waiting for packet_size bytes in m_recv_buffer before calling dispatch_message.

Framing is done here directly off ByteStream.readExactly rather than through PeerMessage.tryReadMessage (which assumes a pre-filled buffer): read 4 length bytes, decode the unsigned length, treat 0 as a keep-alive, then readExactly(len) the body and hand it to PeerMessage.decode.

Before invoking onMessage, this updates the local connection state for the protocol-defining messages so the orchestrator always sees a consistent state:

Everything else (requests we receive, blocks we receive, cancels, fast-extension hints, the extended protocol) is decoded and forwarded without side effects. Those drive disk and picker policy, which lives in the orchestrator. onMessage is invoked for every decoded message, including the state-changing ones, so the orchestrator can react (e.g. pick blocks on unchoke).

The loop ends normally when ByteStream.readExactly reports end-of-stream; frame-length sanity is enforced (BadFrameLengthException for an unaddressable length, ProtocolException for a length exceeding maxMessageLength).

Parameters

onMessage

invoked for each decoded message after state is updated.

maxMessageLength

reject any single message body larger than this (a hostile-peer guard; defaults to DEFAULT_MAX_MESSAGE_LENGTH, generous enough for a max-size piece block).