From ed7bd612303a0f7664ed8a8473881dc719c3e4b2 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Sun, 15 Sep 2019 20:48:16 +0200 Subject: [PATCH] Sanitize types in createType (#1395) --- .../types/src/codec/create/getTypeDef.spec.ts | 47 +++- packages/types/src/codec/create/getTypeDef.ts | 4 +- packages/types/src/codec/create/sanitize.ts | 206 ++++++++++++++++++ packages/types/src/primitive/Type.ts | 204 +---------------- 4 files changed, 248 insertions(+), 213 deletions(-) create mode 100644 packages/types/src/codec/create/sanitize.ts diff --git a/packages/types/src/codec/create/getTypeDef.spec.ts b/packages/types/src/codec/create/getTypeDef.spec.ts index c17e96711a..e5e2a3123c 100644 --- a/packages/types/src/codec/create/getTypeDef.spec.ts +++ b/packages/types/src/codec/create/getTypeDef.spec.ts @@ -18,15 +18,15 @@ describe('getTypeDef', (): void => { it('does not allow invalid vectors, end >', (): void => { expect( (): TypeDef => getTypeDef('Vec'/); + ).toThrow(/Unable to find closing matching/); }); it('returns a type structure', (): void => { expect( - getTypeDef('(u32, Compact, Vec, Option, DoubleMap, (Text, Vec<(Bool, u128)>))') + getTypeDef('(u32, Compact, Vec, Option, DoubleMap, (Text,Vec<(Bool,u128)>))') ).toEqual({ info: TypeDefInfo.Tuple, - type: '(u32, Compact, Vec, Option, DoubleMap, (Text, Vec<(Bool, u128)>))', + type: '(u32,Compact,Vec,Option,DoubleMap,(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, 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, diff --git a/packages/types/src/codec/create/getTypeDef.ts b/packages/types/src/codec/create/getTypeDef.ts index 8ddaeb6f43..8131c6c629 100644 --- a/packages/types/src/codec/create/getTypeDef.ts +++ b/packages/types/src/codec/create/getTypeDef.ts @@ -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 => diff --git a/packages/types/src/codec/create/sanitize.ts b/packages/types/src/codec/create/sanitize.ts new file mode 100644 index 0000000000..85a04b4791 --- /dev/null +++ b/packages/types/src/codec/create/sanitize.ts @@ -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 ::Inherent -> InherentOfflineReport + _alias('::Inherent', 'InherentOfflineReport'), + // alias TreasuryProposal from Proposal> + _alias('Proposal>', 'TreasuryProposal'), + // + _cleanupCompact(), + // Remove all the trait prefixes + _removeTraits(), + // remove PairOf -> (T, T) + _removePairOf(), + // remove boxing, `Box` -> `Proposal` + _removeWrap('Box'), + // remove generics, `MisbehaviorReport` -> `MisbehaviorReport` + _removeGenerics(), + // alias String -> Text (compat with jsonrpc methods) + _alias('String', 'Text'), + // alias () -> Null + _alias('\\(\\)', 'Null'), + // alias Vec -> Bytes + _alias('Vec', '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, >::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::` to end up as `` + .replace(/T::/g, '') + // anything `Self::` to end up as `` + .replace(/Self::/g, '') + // `system::` with `` - basically we find `` + .replace(/system::/g, '') + // replace `::` (whitespaces were removed above) + .replace(/::/g, '') + // replace `::` (whitespaces were removed above) + .replace(/::/g, '') + // replace `::` (whitespaces were removed above) + .replace(/::/g, '') + // replace + .replace(//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 +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(); +} diff --git a/packages/types/src/primitive/Type.ts b/packages/types/src/primitive/Type.ts index 771548a341..ee3c18eed1 100644 --- a/packages/types/src/primitive/Type.ts +++ b/packages/types/src/primitive/Type.ts @@ -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 ::Inherent -> InherentOfflineReport - Type._alias('::Inherent', 'InherentOfflineReport'), - // alias TreasuryProposal from Proposal> - Type._alias('Proposal>', 'TreasuryProposal'), - // - Type._cleanupCompact(), - // Remove all the trait prefixes - Type._removeTraits(), - // remove PairOf -> (T, T) - Type._removePairOf(), - // remove boxing, `Box` -> `Proposal` - Type._removeWrap('Box'), - // remove generics, `MisbehaviorReport` -> `MisbehaviorReport` - Type._removeGenerics(), - // alias String -> Text (compat with jsonrpc methods) - Type._alias('String', 'Text'), - // alias () -> Null - Type._alias('\\(\\)', 'Null'), - // alias Vec -> Bytes - Type._alias('Vec', '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, >::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::` to end up as `` - .replace(/T::/g, '') - // anything `Self::` to end up as `` - .replace(/Self::/g, '') - // `system::` with `` - basically we find `` - .replace(/system::/g, '') - // replace `::` (whitespaces were removed above) - .replace(/::/g, '') - // replace `::` (whitespaces were removed above) - .replace(/::/g, '') - // replace `::` (whitespaces were removed above) - .replace(/::/g, '') - // replace - .replace(//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 - 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 */