Skip to content
Closed
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/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -405,16 +405,20 @@ export class ContainerType<Fields extends Record<string, Type<unknown>>> extends
* - For variable size fields does a first pass over the fixed section to read offsets
*/
getFieldRanges(data: DataView, start: number, end: number): BytesRange[] {
const size = end - start;
if (this.variableOffsetsPosition.length === 0) {
// Validate fixed length container
const size = end - start;
if (size !== this.fixedEnd) {
throw Error(`${this.typeName} size ${size} not equal fixed size ${this.fixedEnd}`);
}

return this.fieldRangesFixedLen;
}

if (size < this.fixedEnd) {
throw Error(`${this.typeName} size ${size} less than fixed section size ${this.fixedEnd}`);
}

// Read offsets in one pass
const offsets = readVariableOffsets(data, start, end, this.fixedEnd, this.variableOffsetsPosition);
offsets.push(end - start); // The offsets are relative to the start
Expand Down
10 changes: 9 additions & 1 deletion packages/ssz/src/type/profile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,12 @@ export class ProfileType<Fields extends Record<string, Type<unknown>>> extends C
* - offsets are relative to the start of serialized active fields, after the Bitvector[N]
*/
getFieldRanges(data: ByteViews, start: number, end: number): {optionalFields: BitArray; fieldRanges: BytesRange[]} {
const size = end - start;
const optionalFieldsByteLen = Math.ceil(this.optionalFieldsCount / 8);
if (size < optionalFieldsByteLen) {
throw Error(`${this.typeName} size ${size} less than optional fields size ${optionalFieldsByteLen}`);
}

const optionalFields = new BitArray(
data.uint8Array.subarray(start, start + optionalFieldsByteLen),
this.optionalFieldsCount
Expand All @@ -540,7 +545,6 @@ export class ProfileType<Fields extends Record<string, Type<unknown>>> extends C

if (variableOffsetsPosition.length === 0) {
// Validate fixed length container
const size = end - start;
if (size !== fixedEnd + optionalFieldsByteLen) {
throw Error(
`${this.typeName} size ${size} not equal fixed end plus optionalFieldsByteLen ${
Expand All @@ -552,6 +556,10 @@ export class ProfileType<Fields extends Record<string, Type<unknown>>> extends C
return {optionalFields, fieldRanges: fieldRangesFixedLen};
}

if (size < fixedEnd + optionalFieldsByteLen) {
throw Error(`${this.typeName} size ${size} less than fixed section size ${fixedEnd + optionalFieldsByteLen}`);
}

// Read offsets in one pass
const offsets = readVariableOffsets(
data.dataView,
Expand Down
6 changes: 5 additions & 1 deletion packages/ssz/src/type/progressiveContainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -418,14 +418,18 @@ export class ProgressiveContainerType<Fields extends Record<string, Type<unknown
}

getFieldRanges(data: DataView, start: number, end: number): BytesRange[] {
const size = end - start;
if (this.variableOffsetsPosition.length === 0) {
const size = end - start;
if (size !== this.fixedEnd) {
throw Error(`${this.typeName} size ${size} not equal fixed size ${this.fixedEnd}`);
}
return this.fieldRangesFixedLen;
}

if (size < this.fixedEnd) {
throw Error(`${this.typeName} size ${size} less than fixed section size ${this.fixedEnd}`);
}

const offsets = readVariableOffsets(data, start, end, this.fixedEnd, this.variableOffsetsPosition);
offsets.push(end - start);

Expand Down
10 changes: 9 additions & 1 deletion packages/ssz/src/type/stableContainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -578,8 +578,13 @@ export class StableContainerType<Fields extends Record<string, Type<unknown>>> e
* `activeFields` is a bitvector prepended to the serialized data.
*/
getFieldRanges(data: ByteViews, start: number, end: number): {activeFields: BitArray; fieldRanges: BytesRange[]} {
const size = end - start;
// this.maxChunkCount = maxFields
const activeFieldsByteLen = Math.ceil(this.maxChunkCount / 8);
if (size < activeFieldsByteLen) {
throw Error(`${this.typeName} size ${size} less than active fields size ${activeFieldsByteLen}`);
}

// active fields bitvector, do not mutate
const activeFields = new BitArray(data.uint8Array.subarray(start, start + activeFieldsByteLen), this.maxChunkCount);

Expand All @@ -590,14 +595,17 @@ export class StableContainerType<Fields extends Record<string, Type<unknown>>> e

if (variableOffsetsPosition.length === 0) {
// Validate fixed length container
const size = end - start;
if (size !== fixedEnd) {
throw Error(`${this.typeName} size ${size} not equal fixed size ${fixedEnd}`);
}

return {activeFields, fieldRanges: fieldRangesFixedLen};
}

if (size < fixedEnd) {
throw Error(`${this.typeName} size ${size} less than fixed section size ${fixedEnd}`);
}

// Read offsets in one pass
const offsets = readVariableOffsets(
data.dataView,
Expand Down
108 changes: 108 additions & 0 deletions packages/ssz/test/unit/byType/container/shortInput.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import {describe, expect, it, vi} from "vitest";
import {
BitListType,
ByteListType,
ContainerNodeStructType,
ContainerType,
UintNumberType,
} from "../../../../src/index.ts";

for (const Container of [ContainerType, ContainerNodeStructType]) {
const type = new Container({number: new UintNumberType(4), bytes: new ByteListType(8)});

describe(`${type.typeName} short input`, () => {
for (const inputKind of ["Uint8Array", "Buffer"] as const) {
const createInput = (bytes: Uint8Array): Uint8Array => (inputKind === "Buffer" ? Buffer.from(bytes) : bytes);

for (const method of ["deserialize", "deserializeToView", "deserializeToViewDU"] as const) {
it.each([0, 2, 7])(`rejects %i bytes without a DataView RangeError (${inputKind}, ${method})`, (size) => {
const bytes = createInput(new Uint8Array(size));
let error: unknown;
try {
type[method](bytes);
} catch (e) {
error = e;
}

expect(error).toBeInstanceOf(Error);
expect(error).not.toBeInstanceOf(RangeError);
expect((error as Error).message).to.equal(`${type.typeName} size ${size} less than fixed section size 8`);
});

it(`accepts a complete fixed section with an empty list (${inputKind}, ${method})`, () => {
const value = {number: 42, bytes: new Uint8Array()};
const serialized = type.serialize(value);
const backing = createInput(Uint8Array.from([0xff, ...serialized, 0xff]));
const bytes = backing.subarray(1, backing.length - 1);

expect(bytes.length).to.equal(type.fixedEnd);
if (method === "deserialize") {
expect(type.deserialize(bytes)).to.deep.equal(value);
} else {
expect(type[method](bytes).serialize()).to.deep.equal(serialized);
}
expect(Array.from(backing)).to.deep.equal([0xff, ...serialized, 0xff]);
});

it(`rejects a short nested container (${inputKind}, ${method})`, () => {
const parent = new ContainerType({child: type, tail: new ByteListType(8)});
const bytes = createInput(new Uint8Array(18));
const dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
dataView.setUint32(0, 8, true);
dataView.setUint32(4, 10, true);
// The child's offset would be read from the following field.
dataView.setUint32(12, type.fixedEnd, true);

expect(() => parent[method](bytes)).toThrow(`${type.typeName} size 2 less than fixed section size 8`);
});
}
}

for (const method of ["value_deserializeFromBytes", "tree_deserializeFromBytes"] as const) {
it(`rejects a short field before reading outside its range (${method})`, () => {
const uint8Array = new Uint8Array(32);
const dataView = new DataView(uint8Array.buffer);
// The offset is readable in the backing view, but lies outside the field's [8, 10) range.
dataView.setUint32(12, type.fixedEnd, true);
const readOffset = vi.spyOn(dataView, "getUint32");

try {
expect(() => type[method]({uint8Array, dataView}, 8, 10)).toThrow(
`${type.typeName} size 2 less than fixed section size 8`
);
expect(readOffset).not.toHaveBeenCalled();
} finally {
readOffset.mockRestore();
}
});
}

it("checks the whole fixed section even when the offset itself is readable", () => {
const reversed = new Container({bytes: new ByteListType(8), number: new UintNumberType(4)});
const bytes = new Uint8Array(7);
const dataView = new DataView(bytes.buffer);
dataView.setUint32(0, 8, true);
const readOffset = vi.spyOn(dataView, "getUint32");

try {
expect(() => reversed.getFieldRanges(dataView, 0, bytes.length)).toThrow(
`${reversed.typeName} size 7 less than fixed section size 8`
);
expect(readOffset).not.toHaveBeenCalled();
} finally {
readOffset.mockRestore();
}
});
});
}

it("keeps field validation when the fixed section is complete", () => {
const type = new ContainerType({bits: new BitListType(8)});
const bytes = Uint8Array.of(4, 0, 0, 0);

expect(bytes.length).to.equal(type.fixedEnd);
expect(bytes.length).to.be.lessThan(type.minSize);
expect(() => type.deserialize(bytes)).toThrow("BitList requires a padding bit");
expect(() => type.deserializeToView(bytes)).toThrow("BitList requires a padding bit");
expect(() => type.deserializeToViewDU(bytes)).toThrow("BitList requires a padding bit");
});
102 changes: 102 additions & 0 deletions packages/ssz/test/unit/containerVariants-shortInput.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import {describe, expect, it, vi} from "vitest";
import {
BitArray,
ByteListType,
OptionalType,
ProfileType,
ProgressiveContainerType,
StableContainerType,
UintNumberType,
} from "../../src/index.ts";

const fields = {number: new UintNumberType(4), bytes: new ByteListType(8)};
const optionalFields = {...fields, bytes: new OptionalType(fields.bytes)};

for (const {type, prefixSize, fixedSize} of [
{type: new ProgressiveContainerType(fields, [true, true]), prefixSize: 0, fixedSize: 8},
{type: new StableContainerType(fields, 16), prefixSize: 2, fixedSize: 10},
{type: new ProfileType(fields, BitArray.fromBoolArray([true, true])), prefixSize: 0, fixedSize: 8},
{type: new ProfileType(optionalFields, BitArray.fromBoolArray([true, true])), prefixSize: 1, fixedSize: 9},
]) {
describe(`${type.typeName} short input`, () => {
const value = {number: 42, bytes: new Uint8Array()};
const serialized = type.serialize(value);

for (const inputKind of ["Uint8Array", "Buffer"] as const) {
const createInput = (bytes: Uint8Array): Uint8Array => (inputKind === "Buffer" ? Buffer.from(bytes) : bytes);
for (const method of ["deserialize", "deserializeToView", "deserializeToViewDU"] as const) {
it.each([...new Set([0, prefixSize, fixedSize - 1])])(
`rejects %i bytes before decoding (${inputKind}, ${method})`,
(size) => {
const bytes = createInput(serialized.subarray(0, size));
expect(() => type[method](bytes)).toThrow(`${type.typeName} size ${size} less than`);
}
);

it(`accepts the fixed section with an empty list (${inputKind}, ${method})`, () => {
const backing = createInput(Uint8Array.from([0xff, ...serialized, 0xff]));
const bytes = backing.subarray(1, backing.length - 1);
expect(bytes.length).to.equal(fixedSize);
if (method === "deserialize") {
expect(type.deserialize(bytes)).to.deep.equal(value);
} else {
expect(type[method](bytes).serialize()).to.deep.equal(serialized);
}
expect(Array.from(backing)).to.deep.equal([0xff, ...serialized, 0xff]);
});
}
}

for (const method of ["value_deserializeFromBytes", "tree_deserializeFromBytes"] as const) {
it(`rejects a short field within a larger buffer before reading offsets (${method})`, () => {
const uint8Array = new Uint8Array(32);
uint8Array.set(serialized, 5);
const dataView = new DataView(uint8Array.buffer);
const readOffset = vi.spyOn(dataView, "getUint32");
try {
expect(() => type[method]({uint8Array, dataView}, 5, 5 + fixedSize - 1)).toThrow(
`${type.typeName} size ${fixedSize - 1} less than fixed section size ${fixedSize}`
);
expect(readOffset).not.toHaveBeenCalled();
} finally {
readOffset.mockRestore();
}
});

if (prefixSize > 0) {
it(`rejects a truncated bitmap before creating its view (${method})`, () => {
const uint8Array = new Uint8Array(32);
uint8Array.set(serialized, 5);
const dataView = new DataView(uint8Array.buffer);
const sliceBitmap = vi.spyOn(uint8Array, "subarray");
try {
expect(() => type[method]({uint8Array, dataView}, 5, 5 + prefixSize - 1)).toThrow(
`${type.typeName} size ${prefixSize - 1} less than`
);
expect(sliceBitmap).not.toHaveBeenCalled();
} finally {
sliceBitmap.mockRestore();
}
});
}
}
});
}

const allOptional = Object.fromEntries(
Array.from({length: 9}, (_, i) => [`field${i}`, new OptionalType(new ByteListType(8))])
);
for (const type of [
new StableContainerType(allOptional, 16),
new ProfileType(allOptional, BitArray.fromBoolArray(Array(9).fill(true))),
]) {
it(`${type.typeName} accepts absent optional fields and rejects a truncated bitmap`, () => {
const value = Object.fromEntries(Object.keys(allOptional).map((key) => [key, null]));
const bytes = type.serialize(value);
expect(Array.from(bytes)).to.deep.equal([0, 0]);
expect(type.deserialize(bytes)).to.deep.equal(value);
expect(type.deserializeToView(bytes).serialize()).to.deep.equal(bytes);
expect(type.deserializeToViewDU(bytes).serialize()).to.deep.equal(bytes);
expect(() => type.deserialize(bytes.subarray(0, 1))).toThrow(`${type.typeName} size 1 less than`);
});
}
Loading