diff --git a/packages/portalnetwork/src/wire/utp/Socket/ContentReader.ts b/packages/portalnetwork/src/wire/utp/Socket/ContentReader.ts index 60416b005..d07ce25dc 100644 --- a/packages/portalnetwork/src/wire/utp/Socket/ContentReader.ts +++ b/packages/portalnetwork/src/wire/utp/Socket/ContentReader.ts @@ -64,9 +64,8 @@ export class ContentReader { } readPacket(payload: Uint8Array) { - this.nextDataNr!++ - // Reset to 0 since ackNr and seqNr are 16 bit unsigned integers - if (this.nextDataNr! > 65535) this.nextDataNr! = 0 + // Wrap seqNr back to 0 when it exceeds 16-bit max integer + this.nextDataNr! = (this.nextDataNr! + 1) % 65536 this.bytes.push(...payload) this.logger.extend('BYTES')( `Current stream: ${this.bytes.length} / ${this.bytesExpected} bytes. ${this.bytesExpected - this.bytes.length} bytes till end of content.`, diff --git a/packages/portalnetwork/src/wire/utp/Socket/ContentWriter.ts b/packages/portalnetwork/src/wire/utp/Socket/ContentWriter.ts index 29fcdb313..f4663b438 100644 --- a/packages/portalnetwork/src/wire/utp/Socket/ContentWriter.ts +++ b/packages/portalnetwork/src/wire/utp/Socket/ContentWriter.ts @@ -33,11 +33,8 @@ export class ContentWriter { this.logger( `Sending ST-DATA ${this.sentChunks.length}/${totalChunks} -- SeqNr: ${this.seqNr}`, ) - this.seqNr = this.sentChunks.slice(-1)[0] + 1 - // Reset to 0 since ackNr and seqNr are 16 bit unsigned integers - if (this.seqNr > 65535) { - this.seqNr = 0 - } + // Wrap seqNr back to 0 when it exceeds 16-bit max integer + this.seqNr = (this.sentChunks[this.sentChunks.length - 1] + 1) % 65536 await this.socket.sendDataPacket(bytes) return } @@ -62,10 +59,7 @@ export class ContentWriter { const end = arrayMod.length > 512 ? 512 : undefined dataChunks[i] = [seqNr, arrayMod.subarray(start, end)] arrayMod = arrayMod.subarray(end) - seqNr++ - if (seqNr > 65535) { - seqNr = 0 - } // Reset to 0 if next sequence number > 65535 + seqNr = (seqNr + 1) % 65536 // Wrap seqNr back to 0 when it exceeds 16-bit max integer } this.logger(`Ready to send ${total} Packets starting at SeqNr: ${this.startingSeqNr}`) return dataChunks