From d16f42dffda45e05a436537c63f2a042eb614939 Mon Sep 17 00:00:00 2001 From: yinbowen-dc <65101280+yinbowen-dc@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:02:05 +0800 Subject: [PATCH] fix: preserve bitlist inputs when reusing byte buffers --- packages/ssz/src/type/abstract.ts | 6 +- packages/ssz/src/type/bitList.ts | 25 +++--- packages/ssz/src/type/progressiveBitList.ts | 6 +- .../unit/byType/bitList/reuseBytes.test.ts | 80 +++++++++++++++++++ 4 files changed, 99 insertions(+), 18 deletions(-) create mode 100644 packages/ssz/test/unit/byType/bitList/reuseBytes.test.ts diff --git a/packages/ssz/src/type/abstract.ts b/packages/ssz/src/type/abstract.ts index df5a304a..0677e324 100644 --- a/packages/ssz/src/type/abstract.ts +++ b/packages/ssz/src/type/abstract.ts @@ -120,7 +120,11 @@ export abstract class Type { return uint8Array; } - /** Deserialize binary data to value */ + /** + * Deserialize binary data to value. + * With `reuseBytes`, fields may share the input buffer. Non-byte-aligned bitlists + * are still copied so removing their padding bit does not modify the input. + */ deserialize(uint8Array: Uint8Array, opts?: {reuseBytes?: boolean}): V { const dataView = new DataView(uint8Array.buffer, uint8Array.byteOffset, uint8Array.byteLength); return this.value_deserializeFromBytes({uint8Array, dataView}, 0, uint8Array.length, opts?.reuseBytes); diff --git a/packages/ssz/src/type/bitList.ts b/packages/ssz/src/type/bitList.ts index 94d97257..9ca32cb0 100644 --- a/packages/ssz/src/type/bitList.ts +++ b/packages/ssz/src/type/bitList.ts @@ -144,11 +144,7 @@ export class BitListType extends BitArrayType { end: number, reuseBytes?: boolean ): BitArrayDeserialized { - const {uint8Array, bitLen} = deserializeUint8ArrayBitListFromBytes(data, start, end, reuseBytes); - if (bitLen > this.limitBits) { - throw Error(`bitLen over limit ${bitLen} > ${this.limitBits}`); - } - return {uint8Array, bitLen}; + return deserializeUint8ArrayBitListFromBytes(data, start, end, reuseBytes, this.limitBits); } } @@ -158,7 +154,8 @@ export function deserializeUint8ArrayBitListFromBytes( data: Uint8Array, start: number, end: number, - reuseBytes?: boolean + reuseBytes?: boolean, + limitBits = Number.POSITIVE_INFINITY ): BitArrayDeserialized { if (end > data.length) { throw Error(`BitList attempting to read byte ${end} of data length ${data.length}`); @@ -174,17 +171,21 @@ export function deserializeUint8ArrayBitListFromBytes( throw new Error("Invalid deserialized bitlist, padding bit required"); } + const lastByteBitLength = lastByte.toString(2).length - 1; + const bitLen = (size - 1) * 8 + lastByteBitLength; + // Check the limit before allocating a copy of untrusted input. + if (bitLen > limitBits) { + throw Error(`bitLen over limit ${bitLen} > ${limitBits}`); + } + if (lastByte === 1) { const uint8Array = slice(data, start, end - 1, reuseBytes); - const bitLen = (size - 1) * 8; return {uint8Array, bitLen}; } - // the last byte is > 1, so a padding bit will exist in the last byte and need to be removed - const uint8Array = slice(data, start, end, reuseBytes); - // mask lastChunkByte - const lastByteBitLength = lastByte.toString(2).length - 1; - const bitLen = (size - 1) * 8 + lastByteBitLength; + // Clearing an in-byte padding bit must not modify the serialized input, + // even when other fields are allowed to reuse their backing buffer. + const uint8Array = slice(data, start, end); const mask = 0xff >> (8 - lastByteBitLength); uint8Array[size - 1] &= mask; return {uint8Array, bitLen}; diff --git a/packages/ssz/src/type/progressiveBitList.ts b/packages/ssz/src/type/progressiveBitList.ts index b314202c..f1b80568 100644 --- a/packages/ssz/src/type/progressiveBitList.ts +++ b/packages/ssz/src/type/progressiveBitList.ts @@ -158,11 +158,7 @@ export class ProgressiveBitListType extends BitArrayType { end: number, reuseBytes?: boolean ): {uint8Array: Uint8Array; bitLen: number} { - const deserialized = deserializeUint8ArrayBitListFromBytes(data, start, end, reuseBytes); - if (deserialized.bitLen > this.limitBits) { - throw Error(`bitLen over limit ${deserialized.bitLen} > ${this.limitBits}`); - } - return deserialized; + return deserializeUint8ArrayBitListFromBytes(data, start, end, reuseBytes, this.limitBits); } } diff --git a/packages/ssz/test/unit/byType/bitList/reuseBytes.test.ts b/packages/ssz/test/unit/byType/bitList/reuseBytes.test.ts new file mode 100644 index 00000000..cdaf5903 --- /dev/null +++ b/packages/ssz/test/unit/byType/bitList/reuseBytes.test.ts @@ -0,0 +1,80 @@ +import {Buffer} from "node:buffer"; +import {describe, expect, it, vi} from "vitest"; +import {BitArray, BitListType, ByteVectorType, ContainerType, ProgressiveBitListType} from "../../../../src/index.ts"; + +const types = [new BitListType(16), new ProgressiveBitListType({limit: 16}), new ProgressiveBitListType()]; + +for (const type of types) { + for (const inputKind of ["Uint8Array", "Buffer"]) { + describe(`${type.typeName} reuseBytes with ${inputKind}`, () => { + function wrap(serialized: Uint8Array): Uint8Array { + // Use a subarray with nonzero offset and unrelated bytes on both sides. + const backing = + inputKind === "Buffer" + ? Buffer.alloc(serialized.length + 4, 0xa5) + : new Uint8Array(serialized.length + 4).fill(0xa5); + backing.set(serialized, 2); + return backing.subarray(2, serialized.length + 2); + } + + it.each([1, 7, 9, 15])("preserves the input and repeated decoding at %i bits", (bitLen) => { + const serialized = type.serialize(BitArray.fromBoolArray(Array(bitLen).fill(true))); + const input = wrap(serialized); + const backingBefore = Uint8Array.from(new Uint8Array(input.buffer)); + const first = type.deserialize(input, {reuseBytes: true}); + const second = type.deserialize(input, {reuseBytes: true}); + expect(first.bitLen).toBe(bitLen); + expect(second.bitLen).toBe(bitLen); + expect(first.toBoolArray()).toEqual(Array(bitLen).fill(true)); + expect(second.toBoolArray()).toEqual(first.toBoolArray()); + expect(type.serialize(first)).toEqual(serialized); + expect(new Uint8Array(input.buffer)).toEqual(backingBefore); + expect(first.uint8Array.buffer).not.toBe(input.buffer); + }); + + it.each([0, 8, 16])("keeps zero-copy decoding for %i byte-aligned bits", (bitLen) => { + const input = wrap(type.serialize(BitArray.fromBitLen(bitLen))); + const before = Uint8Array.from(input); + const value = type.deserialize(input, {reuseBytes: true}); + expect(value.bitLen).toBe(bitLen); + expect(value.uint8Array.buffer).toBe(input.buffer); + expect(Uint8Array.from(input)).toEqual(before); + expect(type.deserialize(input, {reuseBytes: false}).uint8Array.buffer).not.toBe(input.buffer); + }); + + it("copies the non-aligned bitlist while reusing other container fields", () => { + const container = new ContainerType({bits: type, bytes: new ByteVectorType(4)}); + const serialized = container.serialize({ + bits: BitArray.fromBoolArray([true]), + bytes: Uint8Array.of(1, 2, 3, 4), + }); + const input = wrap(serialized); + const value = container.deserialize(input, {reuseBytes: true}); + expect(value.bits.bitLen).toBe(1); + expect(value.bits.uint8Array.buffer).not.toBe(input.buffer); + expect(value.bytes.buffer).toBe(input.buffer); + expect(Uint8Array.from(input)).toEqual(serialized); + expect(container.deserialize(input, {reuseBytes: true})).toEqual(value); + }); + }); + } +} + +for (const type of types.slice(0, 2)) { + for (const reuseBytes of [false, true]) { + it(`${type.typeName} rejects oversized input before copying (reuseBytes=${reuseBytes})`, () => { + const input = Uint8Array.of(0, 0, 2); // 17 bits, limit 16 + const slice = vi.spyOn(Uint8Array.prototype, "slice"); + try { + expect(() => type.deserialize(input, {reuseBytes})).toThrow("bitLen over limit 17 > 16"); + expect(slice).not.toHaveBeenCalled(); + expect(input).toEqual(Uint8Array.of(0, 0, 2)); + const data = {uint8Array: input, dataView: new DataView(input.buffer)}; + expect(() => type.tree_deserializeFromBytes(data, 0, input.length)).toThrow("bitLen over limit 17 > 16"); + expect(slice).not.toHaveBeenCalled(); + } finally { + slice.mockRestore(); + } + }); + } +}