Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion packages/ssz/src/type/abstract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,11 @@ export abstract class Type<V> {
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);
Expand Down
25 changes: 13 additions & 12 deletions packages/ssz/src/type/bitList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand All @@ -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}`);
Expand All @@ -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};
Expand Down
6 changes: 1 addition & 5 deletions packages/ssz/src/type/progressiveBitList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down
80 changes: 80 additions & 0 deletions packages/ssz/test/unit/byType/bitList/reuseBytes.test.ts
Original file line number Diff line number Diff line change
@@ -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<boolean>(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<boolean>(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();
}
});
}
}
Loading