Use custom hasher for Map (#857)

* Use blake2 instead of two_x

* Add v4

* Update to new v4 static

* Update json

* Revert

* Use hasher enum

* Fix metadata v4 test

* Fix metadata v4 test

* Fix versioned metadata

* refactor & clean

* Use consistent naming

* Make jsons consistent

* Add backward compat

* Fix tests

* Start working on type-storage

* Fix output

* Grumble

* Update to latest static

* Clean code

* Fix imports

* Remove useless imports

* Fix tests

* Use prettier output for toJSON in metadata

* Implement different hashers

* Remove generic storageKey

* Bump version

* Add backwards-compat

* Fix hashing function, use Twox128

* Grumbles

* Add tests
This commit is contained in:
Amaury Martiny
2019-04-25 15:34:35 +02:00
committed by GitHub
parent 38c2215bb1
commit 4dd320fc89
63 changed files with 5622 additions and 1402 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/storage",
"version": "0.77.0-beta.7",
"version": "0.77.0",
"description": "Generic wrapper wrapper around state storage",
"main": "index.js",
"engines": {
@@ -31,7 +31,7 @@
"dependencies": {
"@babel/runtime": "^7.4.3",
"@polkadot/keyring": "^0.76.1",
"@polkadot/types": "^0.77.0-beta.7",
"@polkadot/types": "^0.77.0",
"@polkadot/util": "^0.76.1",
"@polkadot/util-crypto": "^0.76.1"
}
@@ -0,0 +1,27 @@
// Copyright 2017-2019 @polkadot/storage authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Storage } from '../types';
import Metadata from '@polkadot/types/Metadata';
import fromV0 from './v0';
import fromV4 from './v4';
/**
* Extend a storage object with the storage modules & module functions present
* in the metadata.
*
* @param storage - A storage object to be extended.
* @param metadata - The metadata to extend the storage object against.
*/
export default function fromMetadata (metadata: Metadata): Storage {
// For v0-v3 we convert to v0, and use the fromV0 function to parse
if ([0, 1, 2, 3].includes(metadata.version)) {
return fromV0(metadata.asV0);
}
// For v4, we use fromV4 function
return fromV4(metadata.asV4);
}
@@ -0,0 +1,7 @@
// Copyright 2017-2019 @polkadot/storage authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import fromMetadata from './fromMetadata';
export default fromMetadata;
@@ -2,12 +2,11 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { StorageFunctionMetadata, StorageFunctionModifier, StorageFunctionType } from '@polkadot/types/Metadata/v0/Modules';
import { PlainType, StorageFunctionMetadata, StorageFunctionModifier, StorageFunctionType } from '@polkadot/types/Metadata/v0/Storage';
import { StorageFunction } from '@polkadot/types/primitive/StorageKey';
import { Compact, Text, createType, StorageKey, Bytes, U8a } from '@polkadot/types';
import { assert, isNull, isUndefined, stringLowerFirst, stringToU8a, u8aConcat } from '@polkadot/util';
import { xxhashAsU8a } from '@polkadot/util-crypto';
import { PlainType } from '@polkadot/types/Metadata/v2/Storage';
export interface CreateItemOptions {
isUnhashed?: boolean;
@@ -60,7 +59,7 @@ export default function createFunction (section: Text | string, method: Text | s
name: meta.name,
modifier: new StorageFunctionModifier('Required'),
type: new StorageFunctionType(new PlainType(meta.type.asMap.key), 0),
default: new Bytes(),
fallback: new Bytes(),
documentation: meta.documentation
});
storageFn.headKey = new StorageKey(keyFn);
@@ -2,13 +2,13 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ModuleStorage, Storage } from './types';
import { ModuleStorage, Storage } from '../../types';
import MetadataV0 from '@polkadot/types/Metadata/v0';
import { stringLowerFirst } from '@polkadot/util';
import createFunction from './utils/createFunction';
import storage from '.';
import createFunction from './createFunction';
import { storage } from './storage';
/**
* Extend a storage object with the storage modules & module functions present
@@ -17,7 +17,7 @@ import storage from '.';
* @param storage - A storage object to be extended.
* @param metadata - The metadata to extend the storage object against.
*/
export default function fromMetadata (metadata: MetadataV0): Storage {
export default function fromV0 (metadata: MetadataV0): Storage {
return metadata.modules.reduce((result, moduleMetadata) => {
if (moduleMetadata.storage.isNone) {
return result;
@@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Storage } from './types';
import { Storage } from '../../types';
import * as substrate from './substrate';
export const storage: Storage = {
@@ -2,11 +2,11 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { StorageFunctionMetadata, StorageFunctionModifier, StorageFunctionType } from '@polkadot/types/Metadata/v0/Modules';
import { StorageFunctionMetadata, StorageFunctionModifier, StorageFunctionType } from '@polkadot/types/Metadata/v0/Storage';
import { StorageFunction } from '@polkadot/types/primitive/StorageKey';
import { Text, Vector } from '@polkadot/types';
import createFunction from './utils/createFunction';
import createFunction from './createFunction';
interface SubstrateMetadata {
documentation: string;
@@ -22,8 +22,7 @@ const createRuntimeFunction = (method: string, key: string, { documentation, typ
documentation: new Vector(Text, [documentation]),
modifier: new StorageFunctionModifier(1), // default
type: new StorageFunctionType(type, 0),
toJSON: (): any =>
key
toJSON: (): any => key
} as StorageFunctionMetadata,
{
isUnhashed: true,
@@ -47,7 +46,7 @@ export const authorityCount = createRuntimeFunction('authorityCount', ':auth:len
});
export const authorityPrefix = createRuntimeFunction('authorityPrefix', ':auth:', {
documentation: 'Prefix under which authorities are storied.',
documentation: 'Prefix under which authorities are stored.',
type: 'u32'
});
@@ -6,13 +6,13 @@ import { u8aToHex } from '@polkadot/util';
import { Metadata } from '@polkadot/types';
import json from '@polkadot/types/Metadata/v0/static';
import fromMetadata from './fromMetadata';
import fromv0 from '.';
// Use the pre-generated metadata
const metadata = new Metadata(json).asV0;
const newStorage = fromMetadata(metadata);
const newStorage = fromv0(metadata);
describe('fromMetadata', () => {
describe('fromv0', () => {
it('should throw if the storage function expects an argument', () => {
expect(() => newStorage.balances.freeBalance()).toThrowError(/expects one argument/);
});
@@ -0,0 +1,56 @@
// Copyright 2017-2019 @polkadot/storage authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { stringToU8a, u8aConcat } from '@polkadot/util';
import createFunction from './createFunction';
describe('createFunction', () => {
it('should create timestamp.now correctly', () => {
expect(
createFunction(
'Timestamp',
'Now',
{ type: {} } as any
)()
).toEqual(
Uint8Array.from([64, 14, 73, 68, 207, 217, 141, 111, 76, 195, 116, 209, 111, 90, 78, 63, 156]) // Length-prefixed
);
});
it('allows overrides on key (keeping name)', () => {
expect(
createFunction(
'Substrate',
'authorityCount',
{ type: {} } as any,
{
isUnhashed: true,
key: ':auth:len'
}
).method
).toEqual('authorityCount');
});
it('allows overrides on key (unhashed)', () => {
const key = ':auth:len';
expect(
createFunction(
'Substrate',
'authorityCount',
{ type: {} } as any,
{
isUnhashed: true,
key
}
)()
).toEqual(
u8aConcat(
Uint8Array.from([key.length << 2]),
stringToU8a(':auth:len')
)
);
});
});
@@ -0,0 +1,81 @@
// Copyright 2017-2019 @polkadot/storage authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { createType, Bytes, Compact, StorageKey, Text, U8a } from '@polkadot/types';
import { PlainType, StorageFunctionMetadata, StorageFunctionModifier, StorageFunctionType } from '@polkadot/types/Metadata/v4/Storage';
import { StorageFunction } from '@polkadot/types/primitive/StorageKey';
import { assert, isNull, isUndefined, stringLowerFirst, stringToU8a, u8aConcat } from '@polkadot/util';
import getHasher from './getHasher';
export interface CreateItemOptions {
isUnhashed?: boolean;
key?: string;
}
/**
* From the schema of a function in the module's storage, generate the function
* that will return the correct storage key.
*
* @param schema - The function's definition schema to create the function from.
* The schema is taken from state_getMetadata.
* @param options - Additional options when creating the function. These options
* are not known at runtime (from state_getMetadata), they need to be supplied
* by us manually at compile time.
*/
export default function createFunction (section: Text | string, method: Text | string, meta: StorageFunctionMetadata, options: CreateItemOptions = {}): StorageFunction {
const stringKey = options.key
? options.key
: `${section.toString()} ${method.toString()}`;
const rawKey = stringToU8a(stringKey);
// Get the hashing function
// FIXME Hash correctly for double map too
const hasher = meta.type.isMap
? getHasher(meta.type.asMap.hasher)
: getHasher();
// Can only have zero or one argument:
// - storage.balances.freeBalance(address)
// - storage.timestamp.blockPeriod()
const storageFn = (arg?: any): Uint8Array => {
let key = rawKey;
if (meta.type.isMap) {
assert(!isUndefined(arg) && !isNull(arg), `${meta.name} expects one argument`);
const type = meta.type.asMap.key.toString();
const param = createType(type, arg).toU8a(false);
key = u8aConcat(key, param);
}
// StorageKey is a Bytes, so is length-prefixed
return Compact.addLengthPrefix(
options.isUnhashed
? key
: hasher(key)
);
};
if (meta.type.isMap && meta.type.asMap.isLinked) {
// TODO: there needs some better way to do this
const keyHash = new U8a(hasher(`head of ${stringKey}`));
const keyFn: any = () => keyHash;
keyFn.meta = new StorageFunctionMetadata({
name: meta.name,
modifier: new StorageFunctionModifier('Required'),
type: new StorageFunctionType(new PlainType(meta.type.asMap.key), 0),
fallback: new Bytes(),
documentation: meta.documentation
});
storageFn.headKey = new StorageKey(keyFn);
}
storageFn.meta = meta;
storageFn.method = stringLowerFirst(method.toString());
storageFn.section = stringLowerFirst(section.toString());
storageFn.toJSON = (): any => meta.toJSON();
return storageFn as StorageFunction;
}
@@ -0,0 +1,39 @@
// Copyright 2017-2019 @polkadot/storage authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { StorageHasher } from '@polkadot/types/Metadata/v4/Storage';
import { blake2AsU8a, xxhashAsU8a } from '@polkadot/util-crypto';
type HasherInput = string | Buffer | Uint8Array;
type HasherFunction = (data: HasherInput) => Uint8Array;
export default function getHasher (hasher?: StorageHasher): HasherFunction {
// This one is the default for PlainType storage keys
if (!hasher) {
return (data: HasherInput) => xxhashAsU8a(data, 128);
}
if (hasher.isBlake2128) {
return (data: HasherInput) => blake2AsU8a(data, 128);
}
if (hasher.isBlake2256) {
return (data: HasherInput) => blake2AsU8a(data, 256);
}
if (hasher.isTwox128) {
return (data: HasherInput) => xxhashAsU8a(data, 128);
}
if (hasher.isTwox256) {
return (data: HasherInput) => xxhashAsU8a(data, 256);
}
// FIXME Add Twox128Concat
// All cases should be handled above, but if not, return Twox128 for
// backwards-compatbility
return (data: HasherInput) => xxhashAsU8a(data, 128);
}
@@ -0,0 +1,37 @@
// Copyright 2017-2019 @polkadot/storage authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ModuleStorage, Storage } from '../../types';
import MetadataV4 from '@polkadot/types/Metadata/v4';
import { stringLowerFirst } from '@polkadot/util';
import createFunction from './createFunction';
import { storage } from './storage';
/**
* Extend a storage object with the storage modules & module functions present
* in the metadata.
*
* @param storage - A storage object to be extended.
* @param metadata - The metadata to extend the storage object against.
*/
export default function fromV4 (metadata: MetadataV4): Storage {
return metadata.modules.reduce((result, moduleMetadata) => {
if (moduleMetadata.storage.isNone) {
return result;
}
const prefix = moduleMetadata.prefix;
// For access, we change the index names, i.e. Balances.FreeBalance -> balances.freeBalance
result[stringLowerFirst(prefix.toString())] = moduleMetadata.storage.unwrap().reduce((newModule, storageFnMeta) => {
newModule[stringLowerFirst(storageFnMeta.name.toString())] = createFunction(prefix, storageFnMeta.name, storageFnMeta);
return newModule;
}, {} as ModuleStorage);
return result;
}, { ...storage });
}
@@ -0,0 +1,17 @@
// Copyright 2017-2019 @polkadot/storage authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { storage } from './storage';
describe('storage', () => {
it('should return well known keys', () => {
expect(typeof storage.substrate).toBe('object');
expect(storage.substrate.authorityCount).toBeTruthy();
expect(storage.substrate.authorityPrefix).toBeTruthy();
expect(storage.substrate.changesTrieConfig).toBeTruthy();
expect(storage.substrate.code).toBeTruthy();
expect(storage.substrate.extrinsicIndex).toBeTruthy();
expect(storage.substrate.heapPages).toBeTruthy();
});
});
@@ -0,0 +1,10 @@
// Copyright 2017-2019 @polkadot/storage authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Storage } from '../../types';
import * as substrate from './substrate';
export const storage: Storage = {
substrate // Prefill storage with well known keys, as not returned by state_getMetadata
};
@@ -0,0 +1,33 @@
// Copyright 2017-2019 @polkadot/storage authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { authorityCount, authorityPrefix, changesTrieConfig, code, extrinsicIndex, heapPages } from './substrate';
describe('substrate', () => {
it('authorityCount should return the correct storage key', () => {
expect(authorityCount()).toEqual(Uint8Array.from([36, 58, 97, 117, 116, 104, 58, 108, 101, 110])); // Length-prefixed
});
it('authorityPrefix should return the correct storage key', () => {
expect(authorityPrefix()).toEqual(Uint8Array.from([24, 58, 97, 117, 116, 104, 58])); // Length-prefixed
});
it('changesTrieConfig should return the correct storage key', () => {
expect(changesTrieConfig()).toEqual(Uint8Array.from([52, 58, 99, 104, 97, 110, 103, 101, 115, 95, 116, 114, 105, 101])); // Length-prefixed
});
it('code should return the correct storage key', () => {
expect(code()).toEqual(Uint8Array.from([20, 58, 99, 111, 100, 101])); // Length-prefixed
});
it('extrinsicIndex should return the correct storage key', () => {
expect(extrinsicIndex()).toEqual(
Uint8Array.from([64, 58, 101, 120, 116, 114, 105, 110, 115, 105, 99, 95, 105, 110, 100, 101, 120]) // Length-prefixed
);
});
it('heapPages should return the correct storage key', () => {
expect(heapPages()).toEqual(Uint8Array.from([40, 58, 104, 101, 97, 112, 112, 97, 103, 101, 115])); // Length-prefixed
});
});
@@ -0,0 +1,61 @@
// Copyright 2017-2019 @polkadot/storage authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { StorageFunctionMetadata, StorageFunctionModifier, StorageFunctionType } from '@polkadot/types/Metadata/v4/Storage';
import { StorageFunction } from '@polkadot/types/primitive/StorageKey';
import { Text, Vector } from '@polkadot/types';
import createFunction from './createFunction';
interface SubstrateMetadata {
documentation: string;
type: string;
}
// Small helper function to factorize code on this page.
const createRuntimeFunction = (method: string, key: string, { documentation, type }: SubstrateMetadata): StorageFunction =>
createFunction(
new Text('Substrate'),
new Text(method),
{
documentation: new Vector(Text, [documentation]),
modifier: new StorageFunctionModifier(1), // default
type: new StorageFunctionType(type, 0),
toJSON: (): any => key
} as StorageFunctionMetadata,
{
isUnhashed: true,
key
}
);
export const code = createRuntimeFunction('code', ':code', {
documentation: 'Wasm code of the runtime.',
type: 'Bytes'
});
export const heapPages = createRuntimeFunction('heapPages', ':heappages', {
documentation: 'Number of wasm linear memory pages required for execution of the runtime.',
type: 'u64'
});
export const authorityCount = createRuntimeFunction('authorityCount', ':auth:len', {
documentation: 'Number of authorities.',
type: 'u32'
});
export const authorityPrefix = createRuntimeFunction('authorityPrefix', ':auth:', {
documentation: 'Prefix under which authorities are stored.',
type: 'u32'
});
export const extrinsicIndex = createRuntimeFunction('extrinsicIndex', ':extrinsic_index', {
documentation: 'Current extrinsic index (u32) is stored under this key.',
type: 'u32'
});
export const changesTrieConfig = createRuntimeFunction('changesTrieConfig', ':changes_trie', {
documentation: 'Changes trie configuration is stored under this key.',
type: 'u32'
});
@@ -0,0 +1,35 @@
// Copyright 2017-2019 @polkadot/storage authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import testingPairs from '@polkadot/keyring/testingPairs';
import { Metadata } from '@polkadot/types';
import json from '@polkadot/types/Metadata/v4/static';
import { u8aToHex } from '@polkadot/util';
import fromv4 from '.';
const keyring = testingPairs({ type: 'ed25519' });
// Use the pre-generated metadata
const metadata = new Metadata(json).asV4;
const newStorage = fromv4(metadata);
describe('fromv4', () => {
it('should throw if the storage function expects an argument', () => {
expect(() => newStorage.balances.freeBalance()).toThrowError(/expects one argument/);
});
it('should return a value if the storage function does not expect an argument', () => {
expect(() => newStorage.timestamp.now()).not.toThrow();
});
it('should return the correct length-prefixed storage key', () => {
expect(
u8aToHex(
newStorage.balances.freeBalance(keyring.alice.address())
)
).toEqual(
'0x807f864e18e3dd8b58386310d2fe0919eef27c6e558564b7f67f22d99d20f587bb'
);
});
});
+1 -1
View File
@@ -2,6 +2,6 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { storage } from './storage';
import { storage } from './fromMetadata/v0/storage';
export default storage;
+1 -1
View File
@@ -8,5 +8,5 @@ import metadataRpc from '@polkadot/types/Metadata/v0/static';
import fromMetadata from './fromMetadata';
export default fromMetadata(
new Metadata(metadataRpc).asV0
new Metadata(metadataRpc)
);
+1 -5
View File
@@ -4,15 +4,11 @@
import { StorageFunction } from '@polkadot/types/primitive/StorageKey';
import * as substrate from './substrate';
type Substrate = keyof typeof substrate;
export interface ModuleStorage {
[key: string]: StorageFunction;
}
export interface Storage {
[key: string]: ModuleStorage; // Will hold modules returned by state_getMetadata
substrate: { [key in Substrate]: StorageFunction };
substrate: { [key: string]: StorageFunction };
}