From 2be73dc7631b94cb3955e453a0037b6605d4493f Mon Sep 17 00:00:00 2001 From: Alex Potsides Date: Mon, 13 Nov 2023 09:47:38 +0100 Subject: [PATCH] fix: concatenate encrypted data length prefix with data before sending (#387) fix: concatenate data length prefix Sending lots of tiny buffers kills TCP performance, even with `noDelay` disabled. Sending the encrypted data length along with the data in one buffer increases `@libp2p/perf` throughput with noise+yamux from 300-320 MB/s to 320-340 MB/s --- src/crypto/streaming.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/crypto/streaming.ts b/src/crypto/streaming.ts index 771204b..c5cc85e 100644 --- a/src/crypto/streaming.ts +++ b/src/crypto/streaming.ts @@ -1,3 +1,4 @@ +import { concat as uint8ArrayConcat } from 'uint8arrays' import { NOISE_MSG_MAX_LENGTH_BYTES, NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG } from '../constants.js' import { uint16BEEncode } from '../encoder.js' import type { IHandshake } from '../@types/handshake-interface.js' @@ -20,8 +21,10 @@ export function encryptStream (handshake: IHandshake, metrics?: MetricsRegistry) const data = handshake.encrypt(chunk.subarray(i, end), handshake.session) metrics?.encryptedPackets.increment() - yield uint16BEEncode(data.byteLength) - yield data + yield uint8ArrayConcat([ + uint16BEEncode(data.byteLength), + data + ], 2 + data.byteLength) } } }