Sanitize types in createType (#1395)

This commit is contained in:
Jaco Greeff
2019-09-15 20:48:16 +02:00
committed by GitHub
parent cd272e890f
commit ed7bd61230
4 changed files with 248 additions and 213 deletions
@@ -18,15 +18,15 @@ describe('getTypeDef', (): void => {
it('does not allow invalid vectors, end >', (): void => {
expect(
(): TypeDef => getTypeDef('Vec<u64')
).toThrow(/Expected 'Vec<' closing with '>'/);
).toThrow(/Unable to find closing matching/);
});
it('returns a type structure', (): void => {
expect(
getTypeDef('(u32, Compact<u32>, Vec<u64>, Option<u128>, DoubleMap<u128>, (Text, Vec<(Bool, u128)>))')
getTypeDef('(u32, Compact<u32>, Vec<u64>, Option<u128>, DoubleMap<u128>, (Text,Vec<(Bool,u128)>))')
).toEqual({
info: TypeDefInfo.Tuple,
type: '(u32, Compact<u32>, Vec<u64>, Option<u128>, DoubleMap<u128>, (Text, Vec<(Bool, u128)>))',
type: '(u32,Compact<u32>,Vec<u64>,Option<u128>,DoubleMap<u128>,(Text,Vec<(Bool,u128)>))',
sub: [
{
info: TypeDefInfo.Plain,
@@ -66,7 +66,7 @@ describe('getTypeDef', (): void => {
},
{
info: TypeDefInfo.Tuple,
type: '(Text, Vec<(Bool, u128)>)',
type: '(Text,Vec<(Bool,u128)>)',
sub: [
{
info: TypeDefInfo.Plain,
@@ -74,10 +74,10 @@ describe('getTypeDef', (): void => {
},
{
info: TypeDefInfo.Vec,
type: 'Vec<(Bool, u128)>',
type: 'Vec<(Bool,u128)>',
sub: {
info: TypeDefInfo.Tuple,
type: '(Bool, u128)',
type: '(Bool,u128)',
sub: [
{
info: TypeDefInfo.Plain,
@@ -96,15 +96,42 @@ describe('getTypeDef', (): void => {
});
});
it('returns a type structure (sanitized)', (): void => {
expect(
getTypeDef('Vec<(Box<PropIndex>, Proposal,Lookup::Target)>')
).toEqual({
info: TypeDefInfo.Vec,
type: 'Vec<(PropIndex,Proposal,AccountId)>',
sub: {
info: TypeDefInfo.Tuple,
type: '(PropIndex,Proposal,AccountId)',
sub: [
{
info: TypeDefInfo.Plain,
type: 'PropIndex'
},
{
info: TypeDefInfo.Plain,
type: 'Proposal'
},
{
info: TypeDefInfo.Plain,
type: 'AccountId'
}
]
}
});
});
it('returns a type structure (actual)', (): void => {
expect(
getTypeDef('Vec<(PropIndex, Proposal, AccountId)>')
).toEqual({
info: TypeDefInfo.Vec,
type: 'Vec<(PropIndex, Proposal, AccountId)>',
type: 'Vec<(PropIndex,Proposal,AccountId)>',
sub: {
info: TypeDefInfo.Tuple,
type: '(PropIndex, Proposal, AccountId)',
type: '(PropIndex,Proposal,AccountId)',
sub: [
{
info: TypeDefInfo.Plain,
@@ -128,7 +155,7 @@ describe('getTypeDef', (): void => {
getTypeDef('{"balance":"Balance","account_id":"AccountId","log":"(u64, Signature)"}')
).toEqual({
info: TypeDefInfo.Struct,
type: '{"balance":"Balance","account_id":"AccountId","log":"(u64, Signature)"}',
type: '{"balance":"Balance","account_id":"AccountId","log":"(u64,Signature)"}',
sub: [
{
info: TypeDefInfo.Plain,
@@ -143,7 +170,7 @@ describe('getTypeDef', (): void => {
{
info: TypeDefInfo.Tuple,
name: 'log',
type: '(u64, Signature)',
type: '(u64,Signature)',
sub: [
{
info: TypeDefInfo.Plain,
@@ -6,6 +6,7 @@ import { TypeDef, TypeDefExtVecFixed, TypeDefInfo } from './types';
import { assert } from '@polkadot/util';
import sanitize from './sanitize';
import { typeSplit } from './typeSplit';
// decode an enum of either of the following forms
@@ -119,7 +120,8 @@ function extractSubType (type: string, [start, end]: [string, string, any]): str
}
export function getTypeDef (_type: string, name?: string): TypeDef {
const type = _type.toString().trim();
// create the type via Type, allowing types to be sanitized
const type = sanitize(_type);
const value: TypeDef = { info: TypeDefInfo.Plain, name, type };
const nested = nestedExtraction.find((nested): boolean =>
+206
View File
@@ -0,0 +1,206 @@
/* eslint-disable @typescript-eslint/no-use-before-define */
// Copyright 2017-2019 @polkadot/types authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
type Mapper = (value: string) => string;
const ALLOWED_BOXES = ['Compact', 'DoubleMap', 'Linkage', 'Option', 'Vec'];
const mappings: Mapper[] = [
// alias <T::InherentOfflineReport as InherentOfflineReport>::Inherent -> InherentOfflineReport
_alias('<T::InherentOfflineReport as InherentOfflineReport>::Inherent', 'InherentOfflineReport'),
// alias TreasuryProposal from Proposal<T::AccountId, BalanceOf<T>>
_alias('Proposal<T::AccountId, BalanceOf<T>>', 'TreasuryProposal'),
// <T::Balance as HasCompact>
_cleanupCompact(),
// Remove all the trait prefixes
_removeTraits(),
// remove PairOf<T> -> (T, T)
_removePairOf(),
// remove boxing, `Box<Proposal>` -> `Proposal`
_removeWrap('Box'),
// remove generics, `MisbehaviorReport<Hash, BlockNumber>` -> `MisbehaviorReport`
_removeGenerics(),
// alias String -> Text (compat with jsonrpc methods)
_alias('String', 'Text'),
// alias () -> Null
_alias('\\(\\)', 'Null'),
// alias Vec<u8> -> Bytes
_alias('Vec<u8>', 'Bytes'),
// alias &[u8] -> Bytes
_alias('&\\[u8\\]', 'Bytes'),
// alias RawAddress -> Address
_alias('RawAddress', 'Address'),
// alias Lookup::Source to Address (_could_ be AccountId on certain chains)
_alias('Lookup::Source', 'Address'),
// alias Lookup::Target to AccountId (always the case)
_alias('Lookup::Target', 'AccountId'),
// alias for grandpa, as used in polkadot
_alias('grandpa::AuthorityId', 'AuthorityId'),
// specific for SessionIndex (could make this session::, but be conservative)
_alias('session::SessionIndex', 'SessionIndex'),
// HACK duplication between contracts & primitives, however contracts prefixed with exec
_alias('exec::StorageKey', 'ContractStorageKey'),
// Phantom
_alias('rstd::marker::PhantomData', 'PhantomData'),
// flattens tuples with one value, `(AccountId)` -> `AccountId`
_flattenSingleTuple(),
// converts ::Type to Type, <T as Trait<I>>::Proposal -> ::Proposal
_removeColonPrefix()
];
// given a starting index, find the closing >
function _findClosing (value: string, start: number): number {
let depth = 0;
for (let index = start; index < value.length; index++) {
if (value[index] === '>') {
if (!depth) {
return index;
}
depth--;
} else if (value[index] === '<') {
depth++;
}
}
throw new Error(`Unable to find closing matching <> on '${value}' (start ${start})`);
}
function _alias (src: string, dest: string): Mapper {
return (value: string): string => {
return value.replace(
new RegExp(src, 'g'), dest
);
};
}
function _cleanupCompact (): Mapper {
return (value: string): string => {
for (let index = 0; index < value.length; index++) {
if (value[index] !== '<') {
continue;
}
const end = _findClosing(value, index + 1) - 14;
if (value.substr(end, 14) === ' as HasCompact') {
value = `Compact<${value.substr(index + 1, end - index - 1)}>`;
}
}
return value;
};
}
function _flattenSingleTuple (): Mapper {
return (value: string): string => {
return value.replace(/\(([^,]*)\)/, '$1');
};
}
function _removeColonPrefix (): Mapper {
return (value: string): string => {
return value.replace(/^::/, '');
};
}
function _removeGenerics (): Mapper {
return (value: string): string => {
for (let index = 0; index < value.length; index++) {
if (value[index] === '<') {
// check against the allowed wrappers, be it Vec<..>, Option<...> ...
const box = ALLOWED_BOXES.find((box): boolean => {
const start = index - box.length;
return start >= 0 && value.substr(start, box.length) === box;
});
// we have not found anything, unwrap generic innards
if (!box) {
const end = _findClosing(value, index + 1);
value = `${value.substr(0, index)}${value.substr(end + 1)}`;
}
}
}
return value;
};
}
// remove the PairOf wrappers
function _removePairOf (): Mapper {
return (value: string): string => {
for (let index = 0; index < value.length; index++) {
if (value.substr(index, 7) === 'PairOf<') {
const start = index + 7;
const end = _findClosing(value, start);
const type = value.substr(start, end - start);
value = `${value.substr(0, index)}(${type},${type})${value.substr(end + 1)}`;
}
}
return value;
};
}
// remove the type traits
function _removeTraits (): Mapper {
return (value: string): string => {
return value
// remove all whitespaces
.replace(/\s/g, '')
// anything `T::<type>` to end up as `<type>`
.replace(/T::/g, '')
// anything `Self::<type>` to end up as `<type>`
.replace(/Self::/g, '')
// `system::` with `` - basically we find `<T as system::Trait>`
.replace(/system::/g, '')
// replace `<T as Trait>::` (whitespaces were removed above)
.replace(/<TasTrait>::/g, '')
// replace `<T as something::Trait>::` (whitespaces were removed above)
.replace(/<Tas[a-z]+::Trait>::/g, '')
// replace `<Self as Trait>::` (whitespaces were removed above)
.replace(/<SelfasTrait>::/g, '')
// replace <Lookup as StaticLookup>
.replace(/<LookupasStaticLookup>/g, 'Lookup')
// replace `<...>::Type`
.replace(/::Type/g, '')
// replace `wasm::*` eg. `wasm::PrefabWasmModule`
.replace(/wasm::/g, '')
// `sr_std::marker::`
.replace(/sr_std::marker::/g, '');
};
}
// remove wrapping values, i.e. Box<Proposal> -> Proposal
function _removeWrap (_check: string): Mapper {
const check = `${_check}<`;
return (value: string): string => {
let index = 0;
while (index !== -1) {
index = value.indexOf(check);
if (index !== -1) {
const start = index + check.length;
const end = _findClosing(value, start);
value = `${value.substr(0, index)}${value.substr(start, end - start)}${value.substr(end + 1)}`;
}
}
return value;
};
}
export default function santize (value: string): string {
return mappings.reduce((result, fn): string => {
return fn(result);
}, value).trim();
}
+2 -202
View File
@@ -2,11 +2,9 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import sanitize from '../codec/create/sanitize';
import Text from './Text';
type Mapper = (value: string) => string;
const ALLOWED_BOXES = ['Compact', 'Option', 'Vec'];
/**
* @name Type
* @description
@@ -17,49 +15,6 @@ const ALLOWED_BOXES = ['Compact', 'Option', 'Vec'];
export default class Type extends Text {
private _originalLength: number;
private static _mappings: Mapper[] = [
// alias <T::InherentOfflineReport as InherentOfflineReport>::Inherent -> InherentOfflineReport
Type._alias('<T::InherentOfflineReport as InherentOfflineReport>::Inherent', 'InherentOfflineReport'),
// alias TreasuryProposal from Proposal<T::AccountId, BalanceOf<T>>
Type._alias('Proposal<T::AccountId, BalanceOf<T>>', 'TreasuryProposal'),
// <T::Balance as HasCompact>
Type._cleanupCompact(),
// Remove all the trait prefixes
Type._removeTraits(),
// remove PairOf<T> -> (T, T)
Type._removePairOf(),
// remove boxing, `Box<Proposal>` -> `Proposal`
Type._removeWrap('Box'),
// remove generics, `MisbehaviorReport<Hash, BlockNumber>` -> `MisbehaviorReport`
Type._removeGenerics(),
// alias String -> Text (compat with jsonrpc methods)
Type._alias('String', 'Text'),
// alias () -> Null
Type._alias('\\(\\)', 'Null'),
// alias Vec<u8> -> Bytes
Type._alias('Vec<u8>', 'Bytes'),
// alias &[u8] -> Bytes
Type._alias('&\\[u8\\]', 'Bytes'),
// alias RawAddress -> Address
Type._alias('RawAddress', 'Address'),
// alias Lookup::Source to Address (_could_ be AccountId on certain chains)
Type._alias('Lookup::Source', 'Address'),
// alias Lookup::Target to AccountId (always the case)
Type._alias('Lookup::Target', 'AccountId'),
// alias for grandpa, as used in polkadot
Type._alias('grandpa::AuthorityId', 'AuthorityId'),
// specific for SessionIndex (could make this session::, but be conservative)
Type._alias('session::SessionIndex', 'SessionIndex'),
// HACK duplication between contracts & primitives, however contracts prefixed with exec
Type._alias('exec::StorageKey', 'ContractStorageKey'),
// Phantom
Type._alias('rstd::marker::PhantomData', 'PhantomData'),
// flattens tuples with one value, `(AccountId)` -> `AccountId`
Type._flattenSingleTuple(),
// converts ::Type to Type, <T as Trait<I>>::Proposal -> ::Proposal
Type._removeColonPrefix()
];
public constructor (value: Text | Uint8Array | string = '') {
// First decode it with Text
const textValue = new Text(value);
@@ -67,7 +22,7 @@ export default class Type extends Text {
// Then cleanup the textValue to get the @polkadot/types type, and pass the
// sanitized value to constructor
super(
Type.decodeType(
sanitize(
textValue.toString()
)
);
@@ -75,12 +30,6 @@ export default class Type extends Text {
this._originalLength = textValue.encodedLength;
}
private static decodeType (value: string): string {
return Type._mappings.reduce((result, fn): string => {
return fn(result);
}, value).trim();
}
/**
* @description The length of the value when encoded as a Uint8Array
*/
@@ -91,155 +40,6 @@ export default class Type extends Text {
return this._originalLength;
}
// given a starting index, find the closing >
private static _findClosing (value: string, start: number): number {
let depth = 0;
for (let index = start; index < value.length; index++) {
if (value[index] === '>') {
if (!depth) {
return index;
}
depth--;
} else if (value[index] === '<') {
depth++;
}
}
throw new Error(`Unable to find closing matching <> on '${value}' (start ${start})`);
}
private static _alias (src: string, dest: string): Mapper {
return (value: string): string => {
return value.replace(
new RegExp(src, 'g'), dest
);
};
}
private static _cleanupCompact (): Mapper {
return (value: string): string => {
for (let index = 0; index < value.length; index++) {
if (value[index] !== '<') {
continue;
}
const end = Type._findClosing(value, index + 1) - 14;
if (value.substr(end, 14) === ' as HasCompact') {
value = `Compact<${value.substr(index + 1, end - index - 1)}>`;
}
}
return value;
};
}
private static _flattenSingleTuple (): Mapper {
return (value: string): string => {
return value.replace(/\(([^,]*)\)/, '$1');
};
}
private static _removeColonPrefix (): Mapper {
return (value: string): string => {
return value.replace(/^::/, '');
};
}
private static _removeGenerics (): Mapper {
return (value: string): string => {
for (let index = 0; index < value.length; index++) {
if (value[index] === '<') {
// check against the allowed wrappers, be it Vec<..>, Option<...> ...
const box = ALLOWED_BOXES.find((box): boolean => {
const start = index - box.length;
return start >= 0 && value.substr(start, box.length) === box;
});
// we have not found anything, unwrap generic innards
if (!box) {
const end = Type._findClosing(value, index + 1);
value = `${value.substr(0, index)}${value.substr(end + 1)}`;
}
}
}
return value;
};
}
// remove the PairOf wrappers
private static _removePairOf (): Mapper {
return (value: string): string => {
for (let index = 0; index < value.length; index++) {
if (value.substr(index, 7) === 'PairOf<') {
const start = index + 7;
const end = Type._findClosing(value, start);
const type = value.substr(start, end - start);
value = `${value.substr(0, index)}(${type},${type})${value.substr(end + 1)}`;
}
}
return value;
};
}
// remove the type traits
private static _removeTraits (): Mapper {
return (value: string): string => {
return value
// remove all whitespaces
.replace(/\s/g, '')
// anything `T::<type>` to end up as `<type>`
.replace(/T::/g, '')
// anything `Self::<type>` to end up as `<type>`
.replace(/Self::/g, '')
// `system::` with `` - basically we find `<T as system::Trait>`
.replace(/system::/g, '')
// replace `<T as Trait>::` (whitespaces were removed above)
.replace(/<TasTrait>::/g, '')
// replace `<T as something::Trait>::` (whitespaces were removed above)
.replace(/<Tas[a-z]+::Trait>::/g, '')
// replace `<Self as Trait>::` (whitespaces were removed above)
.replace(/<SelfasTrait>::/g, '')
// replace <Lookup as StaticLookup>
.replace(/<LookupasStaticLookup>/g, 'Lookup')
// replace `<...>::Type`
.replace(/::Type/g, '')
// replace `wasm::*` eg. `wasm::PrefabWasmModule`
.replace(/wasm::/g, '')
// `sr_std::marker::`
.replace(/sr_std::marker::/g, '');
};
}
// remove wrapping values, i.e. Box<Proposal> -> Proposal
private static _removeWrap (_check: string): Mapper {
const check = `${_check}<`;
return (value: string): string => {
let index = 0;
while (index !== -1) {
index = value.indexOf(check);
if (index !== -1) {
const start = index + check.length;
const end = Type._findClosing(value, start);
value = `${value.substr(0, index)}${value.substr(start, end - start)}${value.substr(end + 1)}`;
}
}
return value;
};
}
/**
* @description Returns the base runtime type name for this instance
*/