Add explicit Array checks to Vec/Tuple decoding (#5434)

* Add explicit Array checks to Vec/Tuple decoding

* Fixes for tests

* Remove extra else

* Revert Text changes (keep it pin-point)

* No need for isU8a check (already handled)

* Result length check

* stringify logged object
This commit is contained in:
Jaco
2023-01-20 20:15:30 +02:00
committed by GitHub
parent beca267b66
commit f480cdc1ca
5 changed files with 127 additions and 80 deletions
@@ -21,6 +21,15 @@ describe('Tuple', (): void => {
);
});
describe('constructor', (): void => {
it('fails construction on non-Array, non-Hex inputs', (): void => {
// @ts-expect-error We are intentionally passing a non-valid input
expect(() => new Tuple(registry, [Text, Text], '12345')).toThrow(/Expected array input to Tuple decoding, found string/);
// @ts-expect-error We are intentionally passing a non-valid input
expect(() => new Tuple(registry, [Text, Text], {})).toThrow(/Expected array input to Tuple decoding, found object/);
});
});
describe('decoding', (): void => {
const testDecode = (type: string, input: AnyTupleValue): void =>
it(`can decode from ${type}`, (): void => {
+24 -14
View File
@@ -27,25 +27,35 @@ function noopSetDefinition (d: Definition): Definition {
/** @internal */
function decodeTuple (registry: Registry, result: Codec[], value: Exclude<AnyTupleValue, Uint8Array> | undefined, Classes: Definition): [Codec[], number] {
if (isU8a(value) || isHex(value)) {
return decodeU8a(registry, result, u8aToU8a(value), Classes);
}
if (Array.isArray(value)) {
const Types = Classes[0];
const Types = Classes[0];
for (let i = 0; i < Types.length; i++) {
try {
const entry = value?.[i];
for (let i = 0; i < Types.length; i++) {
try {
const entry = value?.[i];
result[i] = entry instanceof Types[i]
? entry
: new Types[i](registry, entry);
} catch (error) {
throw new Error(`Tuple: failed on ${i}:: ${(error as Error).message}`);
result[i] = entry instanceof Types[i]
? entry
: new Types[i](registry, entry);
} catch (error) {
throw new Error(`Tuple: failed on ${i}:: ${(error as Error).message}`);
}
}
return [result, 0];
} else if (isHex(value)) {
return decodeU8a(registry, result, u8aToU8a(value), Classes);
} else if (!value || !result.length) {
const Types = Classes[0];
for (let i = 0; i < Types.length; i++) {
result[i] = new Types[i](registry);
}
return [result, 0];
}
return [result, 0];
throw new Error(`Expected array input to Tuple decoding, found ${typeof value}: ${stringify(value)}`);
}
/**
+63 -49
View File
@@ -24,67 +24,81 @@ describe('Vec', (): void => {
vector = new Vec(registry, Text, ['1', '23', '345', '4567', new Text(registry, '56789')]);
});
it('wraps a sequence of values', (): void => {
expect(vector.length).toEqual(5); // eslint-disable-line
});
describe('constructor', (): void => {
it('fails construction on non-Array, non-Hex inputs', (): void => {
// @ts-expect-error We are intentionally passing a non-valid input
expect(() => new Vec(registry, Text, '12345')).toThrow(/decoding, found string/);
// @ts-expect-error We are intentionally passing a non-valid input
expect(() => new Vec(registry, Text, {})).toThrow(/decoding, found object/);
});
it('has a sane representation for toString', (): void => {
expect(vector.toString()).toEqual('[1, 23, 345, 4567, 56789]');
});
it('allows construction via hex & null values', (): void => {
// @ts-expect-error We are intentionally passing a non-valid input
expect(new Vec(registry, Text, null)).toHaveLength(0);
});
it('encodes with length prefix', (): void => {
expect(vector.toU8a()).toEqual(new Uint8Array([
5 << 2,
1 << 2, 49,
2 << 2, 50, 51,
3 << 2, 51, 52, 53,
4 << 2, 52, 53, 54, 55,
5 << 2, 53, 54, 55, 56, 57
]));
});
it('decodes a complex type via construction', (): void => {
const test = createTypeUnsafe<Vec<ITuple<[PropIndex, AccountId]>>>(registry, 'Vec<(PropIndex, AccountId)>', [new Uint8Array([
4, 10, 0, 0, 0, 209, 114, 167, 76, 218, 76, 134, 89, 18, 195, 43, 160, 168, 10, 87, 174, 105, 171, 174, 65, 14, 92, 203, 89, 222, 232, 78, 47, 68, 50, 219, 79
])]);
it('allows construction via JSON', (): void => {
expect(
new Vec(registry, Text, ['6', '7']).toJSON()
).toEqual(['6', '7']);
});
expect(test[0][0].toNumber()).toEqual(10);
expect(test[0][1].toString()).toEqual('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua');
});
it('allows construction via JSON (string type)', (): void => {
expect(
new Vec(registry, 'u32', ['6', '7']).toJSON()
).toEqual([6, 7]);
});
it('decodes a complex type via construction', (): void => {
const INPUT = '0x08cc0200000000ce0200000001';
const test = createTypeUnsafe<Vec<Codec>>(registry, 'Vec<(u32, [u32; 0], u16)>', [INPUT]);
it('exposes the type', (): void => {
expect(vector.Type).toEqual('Text');
});
expect(test).toHaveLength(2);
expect(test.toHex()).toEqual(INPUT);
});
it('decodes reusing instantiated inputs', (): void => {
const foo = new Text(registry, 'bar');
it('allows construction via JSON', (): void => {
expect(
new Vec(registry, Text, ['6', '7']).toJSON()
).toEqual(['6', '7']);
});
expect(
(new Vec(registry, Text, [foo]))[0]
).toBe(foo);
});
it('allows construction via JSON (string type)', (): void => {
expect(
new Vec(registry, 'u32', ['6', '7']).toJSON()
).toEqual([6, 7]);
});
it('decodes a complex type via construction', (): void => {
const test = createTypeUnsafe<Vec<ITuple<[PropIndex, AccountId]>>>(registry, 'Vec<(PropIndex, AccountId)>', [new Uint8Array([
4, 10, 0, 0, 0, 209, 114, 167, 76, 218, 76, 134, 89, 18, 195, 43, 160, 168, 10, 87, 174, 105, 171, 174, 65, 14, 92, 203, 89, 222, 232, 78, 47, 68, 50, 219, 79
])]);
it('decodes reusing instantiated inputs', (): void => {
const foo = new Text(registry, 'bar');
expect(test[0][0].toNumber()).toEqual(10);
expect(test[0][1].toString()).toEqual('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua');
});
it('decodes a complex type via construction', (): void => {
const INPUT = '0x08cc0200000000ce0200000001';
const test = createTypeUnsafe<Vec<Codec>>(registry, 'Vec<(u32, [u32; 0], u16)>', [INPUT]);
expect(test).toHaveLength(2);
expect(test.toHex()).toEqual(INPUT);
expect(
(new Vec(registry, Text, [foo]))[0]
).toBe(foo);
});
});
describe('vector-like functions', (): void => {
it('wraps a sequence of values', (): void => {
expect(vector).toHaveLength(5);
});
it('has a sane representation for toString', (): void => {
expect(vector.toString()).toEqual('[1, 23, 345, 4567, 56789]');
});
it('encodes with length prefix', (): void => {
expect(vector.toU8a()).toEqual(new Uint8Array([
5 << 2,
1 << 2, 49,
2 << 2, 50, 51,
3 << 2, 51, 52, 53,
4 << 2, 52, 53, 54, 55,
5 << 2, 53, 54, 55, 56, 57
]));
});
it('exposes the type', (): void => {
expect(vector.Type).toEqual('Text');
});
it('allows retrieval of a specific item', (): void => {
expect(
vector[2].toString()
+29 -16
View File
@@ -4,7 +4,7 @@
import type { HexString } from '@polkadot/util/types';
import type { Codec, CodecClass, Registry } from '../types';
import { compactFromU8aLim, isU8a, logger, u8aToU8a } from '@polkadot/util';
import { compactFromU8aLim, isHex, isU8a, logger, stringify, u8aToU8a } from '@polkadot/util';
import { AbstractArray } from '../abstract/Array';
import { decodeU8aVec, typeToConstructor } from '../utils';
@@ -22,22 +22,26 @@ function noopSetDefinition <T extends Codec> (d: CodecClass<T>): CodecClass<T> {
return d;
}
function decodeVecLength (value: Uint8Array | HexString | unknown[]): [Uint8Array | unknown[], number, number] {
function decodeVecLength (value: Uint8Array | HexString | unknown[]): [Uint8Array | unknown[] | null, number, number] {
if (Array.isArray(value)) {
return [value, value.length, 0];
} else if (isU8a(value) || isHex(value)) {
const u8a = u8aToU8a(value);
const [startAt, length] = compactFromU8aLim(u8a);
if (length > MAX_LENGTH) {
throw new Error(`Vec length ${length.toString()} exceeds ${MAX_LENGTH}`);
}
return [u8a, length, startAt];
} else if (!value) {
return [null, 0, 0];
}
const u8a = u8aToU8a(value);
const [startAt, length] = compactFromU8aLim(u8a);
if (length > MAX_LENGTH) {
throw new Error(`Vec length ${length.toString()} exceeds ${MAX_LENGTH}`);
}
return [u8a, length, startAt];
throw new Error(`Expected array/hex input to Vec<*> decoding, found ${typeof value}: ${stringify(value)}`);
}
export function decodeVec<T extends Codec> (registry: Registry, result: T[], value: Uint8Array | HexString | unknown[], startAt: number, Type: CodecClass<T>): [number, number] {
export function decodeVec<T extends Codec> (registry: Registry, result: T[], value: Uint8Array | HexString | unknown[] | null, startAt: number, Type: CodecClass<T>): [number, number] {
if (Array.isArray(value)) {
const count = result.length;
@@ -57,9 +61,12 @@ export function decodeVec<T extends Codec> (registry: Registry, result: T[], val
}
}
return [0, 0];
} else if (!value) {
return [0, 0];
}
// we don't need more checks, we already limited it via the length decoding
return decodeU8aVec(registry, result, u8aToU8a(value), startAt, Type);
}
@@ -80,11 +87,17 @@ export class Vec<T extends Codec> extends AbstractArray<T> {
this.#Type = definition || setDefinition(typeToConstructor<T>(registry, Type));
this.initialU8aLength = (
isU8a(decodeFrom)
? decodeU8aVec(registry, this, decodeFrom, startAt, this.#Type)
: decodeVec(registry, this, decodeFrom, startAt, this.#Type)
)[0];
try {
this.initialU8aLength = (
isU8a(decodeFrom)
? decodeU8aVec(registry, this, decodeFrom, startAt, this.#Type)
: decodeVec(registry, this, decodeFrom, startAt, this.#Type)
)[0];
} catch (e) {
console.error(decodeFrom, length, startAt);
throw e;
}
}
public static with<O extends Codec> (Type: CodecClass<O> | string): CodecClass<Vec<O>> {
+2 -1
View File
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import type { Codec } from './codec';
export type AnyJson = string | number | boolean | null | undefined | AnyJson[] | { [index: string]: AnyJson };
@@ -31,4 +32,4 @@ export type UIntBitLength = 8 | 16 | 32 | 64 | 128 | 256;
// as a result of the Polkadot claims module. (Technically we don't need the 520 in here)
export type U8aBitLength = 8 | 16 | 32 | 64 | 128 | 160 | 256 | 264 | 512 | 520 | 1024 | 2048;
export type AnyTupleValue = AnyU8a | (Codec | AnyU8a | AnyNumber | AnyString | undefined | null)[];
export type AnyTupleValue = Exclude<AnyU8a, string> | HexString | (Codec | AnyU8a | AnyNumber | AnyString | undefined | null)[];