Add Identity hasher (#2044)

* Add Identity hasher

* Expand new V11 storage types

* Cleanups, use actual enum keys

* Sort augmented output (fy-by enhancement)

* Map get

* DEFAULT_FN
This commit is contained in:
Jaco Greeff
2020-03-13 13:39:34 +01:00
committed by GitHub
parent 261eebee03
commit 4093ef9ffa
10 changed files with 2305 additions and 2211 deletions
@@ -2,6 +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 metadataDefs from '@polkadot/types/interfaces/metadata/definitions';
import { StorageHasher } from '@polkadot/types/interfaces';
import { u8aConcat, u8aToU8a } from '@polkadot/util';
import { blake2AsU8a, xxhashAsU8a } from '@polkadot/util-crypto';
@@ -10,24 +11,26 @@ export type HasherInput = string | Buffer | Uint8Array;
export type HasherFunction = (data: HasherInput) => Uint8Array;
type HasherCheck = 'isBlake2128' | 'isBlake2128Concat' | 'isBlake2256' | 'isTwox128' | 'isTwox256' | 'isTwox64Concat';
const DEFAULT_FN = (data: HasherInput): Uint8Array => xxhashAsU8a(data, 128);
const DEFAULT = (data: HasherInput): Uint8Array => xxhashAsU8a(data, 128);
const map: Record<HasherCheck, HasherFunction> = {
isBlake2128: (data: HasherInput): Uint8Array => blake2AsU8a(data, 128),
isBlake2128Concat: (data: HasherInput): Uint8Array => u8aConcat(blake2AsU8a(data, 128), u8aToU8a(data)),
isBlake2256: (data: HasherInput): Uint8Array => blake2AsU8a(data, 256),
isTwox128: (data: HasherInput): Uint8Array => xxhashAsU8a(data, 128),
isTwox256: (data: HasherInput): Uint8Array => xxhashAsU8a(data, 256),
isTwox64Concat: (data: HasherInput): Uint8Array => u8aConcat(xxhashAsU8a(data, 64), u8aToU8a(data))
const HASHERS: Record<keyof typeof metadataDefs.types.StorageHasherV11._enum, HasherFunction> = {
Blake2_128: (data: HasherInput): Uint8Array => // eslint-disable-line @typescript-eslint/camelcase
blake2AsU8a(data, 128),
Blake2_128Concat: (data: HasherInput): Uint8Array => // eslint-disable-line @typescript-eslint/camelcase
u8aConcat(blake2AsU8a(data, 128), u8aToU8a(data)),
Blake2_256: (data: HasherInput): Uint8Array => // eslint-disable-line @typescript-eslint/camelcase
blake2AsU8a(data, 256),
Identity: (data: HasherInput): Uint8Array =>
u8aToU8a(data),
Twox128: (data: HasherInput): Uint8Array =>
xxhashAsU8a(data, 128),
Twox256: (data: HasherInput): Uint8Array =>
xxhashAsU8a(data, 256),
Twox64Concat: (data: HasherInput): Uint8Array =>
u8aConcat(xxhashAsU8a(data, 64), u8aToU8a(data))
};
/** @internal */
export default function getHasher (hasher?: StorageHasher): HasherFunction {
const [, fn] = (hasher && Object.entries(map).find(([check]): boolean =>
hasher[check as HasherCheck]
)) || [undefined, DEFAULT];
return fn;
return HASHERS[hasher?.type as 'Identity'] || DEFAULT_FN;
}