diff --git a/packages/util-crypto/src/address/check.ts b/packages/util-crypto/src/address/check.ts index f30327ade..96e6051b0 100644 --- a/packages/util-crypto/src/address/check.ts +++ b/packages/util-crypto/src/address/check.ts @@ -4,7 +4,7 @@ import type { HexString } from '@polkadot/util/types'; import type { Prefix } from './types'; -import { base58Decode } from '../base58/decode'; +import { base58Decode } from '../base58'; import { checkAddressChecksum } from './checksum'; import { defaults } from './defaults'; diff --git a/packages/util-crypto/src/address/checksum.spec.ts b/packages/util-crypto/src/address/checksum.spec.ts index 519785027..71fab79b8 100644 --- a/packages/util-crypto/src/address/checksum.spec.ts +++ b/packages/util-crypto/src/address/checksum.spec.ts @@ -1,7 +1,7 @@ // Copyright 2017-2021 @polkadot/util-crypto authors & contributors // SPDX-License-Identifier: Apache-2.0 -import { base58Decode } from '../base58/decode'; +import { base58Decode } from '../base58'; import { checkAddressChecksum } from './checksum'; describe('checkAddressChecksum', (): void => { diff --git a/packages/util-crypto/src/address/decode.ts b/packages/util-crypto/src/address/decode.ts index 281afb812..0342f1f39 100644 --- a/packages/util-crypto/src/address/decode.ts +++ b/packages/util-crypto/src/address/decode.ts @@ -7,7 +7,7 @@ import type { Prefix } from './types'; // Original implementation: https://github.com/paritytech/polka-ui/blob/4858c094684769080f5811f32b081dd7780b0880/src/polkadot.js#L6 import { assert, isHex, isU8a, u8aToU8a } from '@polkadot/util'; -import { base58Decode } from '../base58/decode'; +import { base58Decode } from '../base58'; import { checkAddressChecksum } from './checksum'; import { defaults } from './defaults'; diff --git a/packages/util-crypto/src/address/encode.ts b/packages/util-crypto/src/address/encode.ts index 1de4bd056..334bdba5c 100644 --- a/packages/util-crypto/src/address/encode.ts +++ b/packages/util-crypto/src/address/encode.ts @@ -7,7 +7,7 @@ import type { Prefix } from './types'; // Original implementation: https://github.com/paritytech/polka-ui/blob/4858c094684769080f5811f32b081dd7780b0880/src/polkadot.js#L34 import { assert, u8aConcat } from '@polkadot/util'; -import { base58Encode } from '../base58/encode'; +import { base58Encode } from '../base58'; import { decodeAddress } from './decode'; import { defaults } from './defaults'; import { sshash } from './sshash'; diff --git a/packages/util-crypto/src/base32/bs32.ts b/packages/util-crypto/src/base32/bs32.ts index e3c65a2e3..65e49eb35 100644 --- a/packages/util-crypto/src/base32/bs32.ts +++ b/packages/util-crypto/src/base32/bs32.ts @@ -3,14 +3,51 @@ import { utils } from 'micro-base'; -export const BASE32_ALPHABET = 'abcdefghijklmnopqrstuvwxyz234567'; +import { createDecode, createEncode, createIs, createValidate } from './helpers'; -// We define our own chain, the default base32 has padding -export const base32 = utils.chain( - utils.radix2(5), - utils.alphabet(BASE32_ALPHABET), - { - decode: (input: string) => input.split(''), - encode: (input: string[]) => input.join('') - } -); +const BASE32_ALPHABET = 'abcdefghijklmnopqrstuvwxyz234567'; + +const BASE32_CONFIG = { + alphabet: BASE32_ALPHABET, + coder: utils.chain( + // We define our own chain, the default base32 has padding + utils.radix2(5), + utils.alphabet(BASE32_ALPHABET), + { + decode: (input: string) => input.split(''), + encode: (input: string[]) => input.join('') + } + ), + ipfsChar: 'b', + type: 'base32' +}; + +/** + * @name base32Validate + * @summary Validates a base32 value. + * @description + * Validates that the supplied value is valid base32, throwing exceptions if not + */ +export const base32Validate = createValidate(BASE32_CONFIG); + +/** +* @name isBase32 +* @description Checks if the input is in base32, returning true/false +*/ +export const isBase32 = createIs(base32Validate); + +/** + * @name base32Decode + * @summary Delookup a base32 value. + * @description + * From the provided input, decode the base32 and return the result as an `Uint8Array`. + */ +export const base32Decode = createDecode(BASE32_CONFIG, base32Validate); + +/** +* @name base32Encode +* @summary Creates a base32 value. +* @description +* From the provided input, create the base32 and return the result as a string. +*/ +export const base32Encode = createEncode(BASE32_CONFIG); diff --git a/packages/util-crypto/src/base32/decode.spec.ts b/packages/util-crypto/src/base32/decode.spec.ts index 32e1b21c8..c246ae335 100644 --- a/packages/util-crypto/src/base32/decode.spec.ts +++ b/packages/util-crypto/src/base32/decode.spec.ts @@ -3,7 +3,7 @@ import { u8aToString } from '@polkadot/util'; -import { base32Decode } from './'; +import { base32Decode } from '.'; describe('base32Decode', (): void => { it('decodes a base32', (): void => { diff --git a/packages/util-crypto/src/base32/decode.ts b/packages/util-crypto/src/base32/decode.ts deleted file mode 100644 index 4267ea018..000000000 --- a/packages/util-crypto/src/base32/decode.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017-2021 @polkadot/util-crypto authors & contributors -// SPDX-License-Identifier: Apache-2.0 - -import { base32 } from './bs32'; -import { base32Validate } from './validate'; - -/** - * @name base32Decode - * @summary Delookup a base32 value. - * @description - * From the provided input, decode the base32 and return the result as an `Uint8Array`. - */ -export function base32Decode (value: string, ipfsCompat = false): Uint8Array { - base32Validate(value, ipfsCompat); - - return base32.decode( - ipfsCompat - ? value.substr(1) - : value - ); -} diff --git a/packages/util-crypto/src/base32/encode.spec.ts b/packages/util-crypto/src/base32/encode.spec.ts index 66716c4c8..e927ff0b7 100644 --- a/packages/util-crypto/src/base32/encode.spec.ts +++ b/packages/util-crypto/src/base32/encode.spec.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { base58Decode } from '../base58'; -import { base32Encode } from './'; +import { base32Encode } from '.'; describe('base32Encode', (): void => { it('encodes to a base32', (): void => { diff --git a/packages/util-crypto/src/base32/encode.ts b/packages/util-crypto/src/base32/encode.ts deleted file mode 100644 index 305fb39fc..000000000 --- a/packages/util-crypto/src/base32/encode.ts +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2017-2021 @polkadot/util-crypto authors & contributors -// SPDX-License-Identifier: Apache-2.0 - -import type { U8aLike } from '@polkadot/util/types'; - -import { u8aToU8a } from '@polkadot/util'; - -import { base32 } from './bs32'; - -/** - * @name base32Encode - * @summary Creates a base32 value. - * @description - * From the provided input, create the base32 and return the result as a string. - */ -export function base32Encode (value: U8aLike, ipfsCompat = false): string { - const out = base32.encode(u8aToU8a(value)); - - return ipfsCompat - ? `b${out}` - : out; -} diff --git a/packages/util-crypto/src/base32/helpers.ts b/packages/util-crypto/src/base32/helpers.ts new file mode 100644 index 000000000..2d2ab543e --- /dev/null +++ b/packages/util-crypto/src/base32/helpers.ts @@ -0,0 +1,77 @@ +// Copyright 2017-2021 @polkadot/util-crypto authors & contributors +// SPDX-License-Identifier: Apache-2.0 + +import type { U8aLike } from '@polkadot/util/types'; + +import { assert, u8aToU8a } from '@polkadot/util'; + +interface Coder { + decode: (value: string) => Uint8Array; + encode: (value: Uint8Array) => string; +} + +interface Config { + alphabet: string; + coder: Coder; + ipfsChar?: string; + regex?: RegExp; + type: string; +} + +type DecodeFn = (value: string, ipfsCompat?: boolean) => Uint8Array; + +type EncodeFn = (value: U8aLike, ipfsCompat?: boolean) => string; + +type ValidateFn = (value?: unknown, ipfsCompat?: boolean) => value is string; + +export function createDecode ({ coder, ipfsChar }: Config, validate: ValidateFn): DecodeFn { + return (value: string, ipfsCompat?: boolean): Uint8Array => { + validate(value, ipfsCompat); + + return coder.decode( + ipfsChar && ipfsCompat + ? value.substr(1) + : value + ); + }; +} + +export function createEncode ({ coder, ipfsChar }: Config): EncodeFn { + return (value: U8aLike, ipfsCompat?: boolean): string => { + const out = coder.encode(u8aToU8a(value)); + + return ipfsChar && ipfsCompat + ? `${ipfsChar}${out}` + : out; + }; +} + +export function createIs (validate: ValidateFn): ValidateFn { + return (value?: unknown, ipfsCompat?: boolean): value is string => { + try { + return validate(value, ipfsCompat); + } catch (error) { + return false; + } + }; +} + +export function createValidate ({ alphabet, ipfsChar, regex, type }: Config): ValidateFn { + return (value?: unknown, ipfsCompat?: boolean): value is string => { + assert(value && typeof value === 'string', () => `Expected non-null, non-empty ${type} string input`); + + if (ipfsChar && ipfsCompat) { + assert(value[0] === ipfsChar, () => `Expected ipfs-compatible ${type} to start with '${ipfsChar}'`); + } + + if (regex) { + assert(regex.test(value), `Invalid ${type} encoding`); + } else { + for (let i = (ipfsCompat ? 1 : 0); i < value.length; i++) { + assert(alphabet.includes(value[i]), () => `Invalid ${type} character "${value[i]}" (0x${value.charCodeAt(i).toString(16)}) at index ${i}`); + } + } + + return true; + }; +} diff --git a/packages/util-crypto/src/base32/index.ts b/packages/util-crypto/src/base32/index.ts index 9aca6eabe..f666de88d 100644 --- a/packages/util-crypto/src/base32/index.ts +++ b/packages/util-crypto/src/base32/index.ts @@ -5,7 +5,4 @@ * @summary Encode and decode base32 values */ -export { base32Decode } from './decode'; -export { base32Encode } from './encode'; -export { base32Validate } from './validate'; -export { isBase32 } from './is'; +export { base32Decode, base32Encode, base32Validate, isBase32 } from './bs32'; diff --git a/packages/util-crypto/src/base32/is.spec.ts b/packages/util-crypto/src/base32/is.spec.ts new file mode 100644 index 000000000..0cf927172 --- /dev/null +++ b/packages/util-crypto/src/base32/is.spec.ts @@ -0,0 +1,30 @@ +// Copyright 2017-2021 @polkadot/util-crypto authors & contributors +// SPDX-License-Identifier: Apache-2.0 + +import { isBase32 } from '.'; + +describe('isBase32', (): void => { + it('validates encoded', (): void => { + expect( + isBase32('afkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', false) + ).toEqual(true); + }); + + it('validates ipfs-compat encoded', (): void => { + expect( + isBase32('bafkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', false) + ).toEqual(true); + }); + + it('fails on invalid', (): void => { + expect( + isBase32('not in base32') + ).toEqual(false); + }); + + it('fails on non-ipfs', (): void => { + expect( + isBase32('afkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', true) + ).toEqual(false); + }); +}); diff --git a/packages/util-crypto/src/base32/is.ts b/packages/util-crypto/src/base32/is.ts deleted file mode 100644 index e6f297b75..000000000 --- a/packages/util-crypto/src/base32/is.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2017-2021 @polkadot/util-crypto authors & contributors -// SPDX-License-Identifier: Apache-2.0 - -import { base32Validate } from './validate'; - -export function testValidator (validate: (value?: string | null, ipfsCompat?: boolean) => boolean, value?: string | null, ipfsCompat?: boolean): boolean { - try { - return validate(value, ipfsCompat); - } catch (error) { - return false; - } -} - -export function isBase32 (value?: string | null, ipfsCompat?: boolean): value is string { - return testValidator(base32Validate, value, ipfsCompat); -} diff --git a/packages/util-crypto/src/base32/validate.spec.ts b/packages/util-crypto/src/base32/validate.spec.ts index 6b470bd6a..c5523ea09 100644 --- a/packages/util-crypto/src/base32/validate.spec.ts +++ b/packages/util-crypto/src/base32/validate.spec.ts @@ -4,9 +4,39 @@ import { base32Validate } from '.'; describe('base32Validate', (): void => { + it('validates encoded', (): void => { + expect( + base32Validate('afkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', false) + ).toEqual(true); + }); + it('validates ipfs-compat encoded', (): void => { expect( - () => base32Validate('bafkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', true) - ).not.toThrow(); + base32Validate('bafkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', true) + ).toEqual(true); + }); + + it('fails on empty', (): void => { + expect( + () => base32Validate('') + ).toThrow(/Expected/); + }); + + it('fails on non-string', (): void => { + expect( + () => base32Validate(true) + ).toThrow(/Expected/); + }); + + it('fails on invalid', (): void => { + expect( + () => base32Validate('not in base32') + ).toThrow(/Invalid/); + }); + + it('fails on non-ipfs', (): void => { + expect( + () => base32Validate('afkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', true) + ).toThrow(/Expected/); }); }); diff --git a/packages/util-crypto/src/base32/validate.ts b/packages/util-crypto/src/base32/validate.ts deleted file mode 100644 index 6085f5d9b..000000000 --- a/packages/util-crypto/src/base32/validate.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2017-2021 @polkadot/util-crypto authors & contributors -// SPDX-License-Identifier: Apache-2.0 - -import { createValidateFn } from '../base58/validate'; -import { BASE32_ALPHABET } from './bs32'; - -/** - * @name base32Validate - * @summary Validates a base32 value. - * @description - * Validates that the supplied value is valid base32 - */ -export const base32Validate = createValidateFn({ alphabet: BASE32_ALPHABET, ipfsChar: 'b', type: 'base32' }); diff --git a/packages/util-crypto/src/base58/bs58.ts b/packages/util-crypto/src/base58/bs58.ts index 6d2398d9f..80febdbf8 100644 --- a/packages/util-crypto/src/base58/bs58.ts +++ b/packages/util-crypto/src/base58/bs58.ts @@ -1,7 +1,43 @@ // Copyright 2017-2021 @polkadot/util-crypto authors & contributors // SPDX-License-Identifier: Apache-2.0 -export { base58 } from 'micro-base'; +import { base58 } from 'micro-base'; -// https://github.com/cryptocoinjs/base-x#alphabets -export const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; +import { createDecode, createEncode, createIs, createValidate } from '../base32/helpers'; + +const BASE58_CONFIG = { + alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz', + coder: base58, + ipfsChar: 'z', + type: 'base58' +}; + +/** + * @name base58Validate + * @summary Validates a base58 value. + * @description + * Validates that the supplied value is valid base58, throwing exceptions if not + */ +export const base58Validate = createValidate(BASE58_CONFIG); + +/** + * @name base58Decode + * @summary Decodes a base58 value. + * @description + * From the provided input, decode the base58 and return the result as an `Uint8Array`. + */ +export const base58Decode = createDecode(BASE58_CONFIG, base58Validate); + +/** +* @name base58Encode +* @summary Creates a base58 value. +* @description +* From the provided input, create the base58 and return the result as a string. +*/ +export const base58Encode = createEncode(BASE58_CONFIG); + +/** +* @name isBase58 +* @description Checks if the input is in base58, returning true/false +*/ +export const isBase58 = createIs(base58Validate); diff --git a/packages/util-crypto/src/base58/decode.ts b/packages/util-crypto/src/base58/decode.ts deleted file mode 100644 index 9b5e3df8b..000000000 --- a/packages/util-crypto/src/base58/decode.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017-2021 @polkadot/util-crypto authors & contributors -// SPDX-License-Identifier: Apache-2.0 - -import { base58 } from './bs58'; -import { base58Validate } from './validate'; - -/** - * @name base58Decode - * @summary Decodes a base58 value. - * @description - * From the provided input, decode the base58 and return the result as an `Uint8Array`. - */ -export function base58Decode (value: string, ipfsCompat?: boolean): Uint8Array { - base58Validate(value, ipfsCompat); - - return base58.decode( - ipfsCompat - ? value.substr(1) - : value - ); -} diff --git a/packages/util-crypto/src/base58/encode.ts b/packages/util-crypto/src/base58/encode.ts deleted file mode 100644 index 88b9df47e..000000000 --- a/packages/util-crypto/src/base58/encode.ts +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2017-2021 @polkadot/util-crypto authors & contributors -// SPDX-License-Identifier: Apache-2.0 - -import type { U8aLike } from '@polkadot/util/types'; - -import { u8aToU8a } from '@polkadot/util'; - -import { base58 } from './bs58'; - -/** - * @name base58Encode - * @summary Creates a base58 value. - * @description - * From the provided input, create the base58 and return the result as a string. - */ -export function base58Encode (value: U8aLike, ipfsCompat?: boolean): string { - const out = base58.encode(u8aToU8a(value)); - - return ipfsCompat - ? `z${out}` - : out; -} diff --git a/packages/util-crypto/src/base58/index.ts b/packages/util-crypto/src/base58/index.ts index 664603631..7b0afaa10 100644 --- a/packages/util-crypto/src/base58/index.ts +++ b/packages/util-crypto/src/base58/index.ts @@ -5,7 +5,4 @@ * @summary Encode and decode base58 values */ -export { base58Decode } from './decode'; -export { base58Encode } from './encode'; -export { base58Validate } from './validate'; -export { isBase58 } from './is'; +export { base58Decode, base58Encode, base58Validate, isBase58 } from './bs58'; diff --git a/packages/util-crypto/src/base58/is.ts b/packages/util-crypto/src/base58/is.ts deleted file mode 100644 index b02998bdf..000000000 --- a/packages/util-crypto/src/base58/is.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2017-2021 @polkadot/util-crypto authors & contributors -// SPDX-License-Identifier: Apache-2.0 - -import { testValidator } from '../base32/is'; -import { base58Validate } from './validate'; - -export function isBase58 (value?: string | null, ipfsCompat?: boolean): value is string { - return testValidator(base58Validate, value, ipfsCompat); -} diff --git a/packages/util-crypto/src/base58/validate.ts b/packages/util-crypto/src/base58/validate.ts deleted file mode 100644 index 1e5544be7..000000000 --- a/packages/util-crypto/src/base58/validate.ts +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2017-2021 @polkadot/util-crypto authors & contributors -// SPDX-License-Identifier: Apache-2.0 - -import { assert } from '@polkadot/util'; - -import { BASE58_ALPHABET } from './bs58'; - -interface CheckConfig { - alphabet: string; - ipfsChar: string; - type: string; -} - -export function createValidateFn ({ alphabet, ipfsChar, type }: CheckConfig): (value?: unknown, ipfsCompat?: boolean) => value is string { - return (value?: unknown, ipfsCompat?: boolean): value is string => { - assert(value && typeof value === 'string', () => `Expected non-null, non-empty ${type} string input`); - assert(!ipfsCompat || value[0] === ipfsChar, () => `Expected ${type} to start with '${ipfsChar}'`); - - for (let i = (ipfsCompat ? 1 : 0); i < value.length; i++) { - assert(alphabet.includes(value[i]), () => `Invalid ${type} character "${value[i]}" (0x${value.charCodeAt(i).toString(16)}) at index ${i}`); - } - - return true; - }; -} - -/** - * @name base58Validate - * @summary Validates a base58 value. - * @description - * Validates that the supplied value is valid base58 - */ -export const base58Validate = createValidateFn({ alphabet: BASE58_ALPHABET, ipfsChar: 'z', type: 'base58' }); diff --git a/packages/util-crypto/src/base64/bs64.ts b/packages/util-crypto/src/base64/bs64.ts index ae7134bab..208cb58ec 100644 --- a/packages/util-crypto/src/base64/bs64.ts +++ b/packages/util-crypto/src/base64/bs64.ts @@ -1,6 +1,43 @@ // Copyright 2017-2021 @polkadot/util-crypto authors & contributors // SPDX-License-Identifier: Apache-2.0 -export { base64 } from 'micro-base'; +import { base64 } from 'micro-base'; -export const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +import { createDecode, createEncode, createIs, createValidate } from '../base32/helpers'; + +const BASE64_CONFIG = { + alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', + coder: base64, + regex: /^(?:[A-Za-z0-9+/]{2}[A-Za-z0-9+/]{2})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/, + type: 'base64' +}; + +/** + * @name base64Validate + * @summary Validates a base64 value. + * @description + * Validates that the supplied value is valid base64 + */ +export const base64Validate = createValidate(BASE64_CONFIG); + +/** + * @name isBase64 + * @description Checks if the input is in base64, returning true/false + */ +export const isBase64 = createIs(base64Validate); + +/** + * @name base64Decode + * @summary Decodes a base64 value. + * @description + * From the provided input, decode the base64 and return the result as an `Uint8Array`. + */ +export const base64Decode = createDecode(BASE64_CONFIG, base64Validate); + +/** + * @name base64Encode + * @summary Creates a base64 value. + * @description + * From the provided input, create the base64 and return the result as a string. + */ +export const base64Encode = createEncode(BASE64_CONFIG); diff --git a/packages/util-crypto/src/base64/decode.ts b/packages/util-crypto/src/base64/decode.ts deleted file mode 100644 index d4ac4f20c..000000000 --- a/packages/util-crypto/src/base64/decode.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2017-2021 @polkadot/util-crypto authors & contributors -// SPDX-License-Identifier: Apache-2.0 - -import { base64 } from './bs64'; -import { base64Validate } from './validate'; - -/** - * @name base64Decode - * @summary Decodes a base64 value. - * @description - * From the provided input, decode the base64 and return the result as an `Uint8Array`. - */ -export function base64Decode (value: string): Uint8Array { - base64Validate(value); - - return base64.decode(value); -} diff --git a/packages/util-crypto/src/base64/encode.ts b/packages/util-crypto/src/base64/encode.ts deleted file mode 100644 index ac0090b0b..000000000 --- a/packages/util-crypto/src/base64/encode.ts +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2017-2021 @polkadot/util-crypto authors & contributors -// SPDX-License-Identifier: Apache-2.0 - -import type { U8aLike } from '@polkadot/util/types'; - -import { u8aToU8a } from '@polkadot/util'; - -import { base64 } from './bs64'; - -/** - * @name base64Encode - * @summary Creates a base64 value. - * @description - * From the provided input, create the base64 and return the result as a string. - */ -export function base64Encode (value: U8aLike): string { - return base64.encode(u8aToU8a(value)); -} diff --git a/packages/util-crypto/src/base64/index.ts b/packages/util-crypto/src/base64/index.ts index 3dedb0a5d..33ddfdb87 100644 --- a/packages/util-crypto/src/base64/index.ts +++ b/packages/util-crypto/src/base64/index.ts @@ -5,9 +5,6 @@ * @summary Encode and decode base64 values */ -export { base64Decode } from './decode'; -export { base64Encode } from './encode'; +export { base64Decode, base64Encode, base64Validate, isBase64 } from './bs64'; export { base64Pad } from './pad'; export { base64Trim } from './trim'; -export { base64Validate } from './validate'; -export { isBase64 } from './is'; diff --git a/packages/util-crypto/src/base64/is.ts b/packages/util-crypto/src/base64/is.ts deleted file mode 100644 index 7ad54ae86..000000000 --- a/packages/util-crypto/src/base64/is.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2017-2021 @polkadot/util-crypto authors & contributors -// SPDX-License-Identifier: Apache-2.0 - -import { base64Validate } from './validate'; - -export function isBase64 (value?: string | null): value is string { - try { - return base64Validate(value); - } catch (error) { - return false; - } -} diff --git a/packages/util-crypto/src/base64/pad.ts b/packages/util-crypto/src/base64/pad.ts index 788caae5d..14c06a1a9 100644 --- a/packages/util-crypto/src/base64/pad.ts +++ b/packages/util-crypto/src/base64/pad.ts @@ -1,6 +1,10 @@ // Copyright 2017-2021 @polkadot/util-crypto authors & contributors // SPDX-License-Identifier: Apache-2.0 +/** + * @name base64Pad + * @description Adds padding characters for correct length + */ export function base64Pad (value: string): string { return value.padEnd(value.length + (value.length % 4), '='); } diff --git a/packages/util-crypto/src/base64/trim.ts b/packages/util-crypto/src/base64/trim.ts index fb81cfccb..743b9c8f3 100644 --- a/packages/util-crypto/src/base64/trim.ts +++ b/packages/util-crypto/src/base64/trim.ts @@ -1,6 +1,10 @@ // Copyright 2017-2021 @polkadot/util-crypto authors & contributors // SPDX-License-Identifier: Apache-2.0 +/** + * @name base64Trim + * @description Trims padding characters + */ export function base64Trim (value: string): string { while (value.length && value[value.length - 1] === '=') { value = value.slice(0, -1); diff --git a/packages/util-crypto/src/base64/validate.ts b/packages/util-crypto/src/base64/validate.ts deleted file mode 100644 index d1e21f66e..000000000 --- a/packages/util-crypto/src/base64/validate.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2017-2021 @polkadot/util-crypto authors & contributors -// SPDX-License-Identifier: Apache-2.0 - -import { assert } from '@polkadot/util'; - -/** - * @name base64Validate - * @summary Validates a base64 value. - * @description - * Validates that the supplied value is valid base64 - */ -export function base64Validate (value?: string | null): value is string { - assert(value && typeof value === 'string', 'Expected non-null, non-empty base64 string input'); - assert(/^(?:[A-Za-z0-9+/]{2}[A-Za-z0-9+/]{2})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value), 'Invalid base64 encoding'); - - return true; -} diff --git a/packages/util-crypto/src/blake2/asU8a.ts b/packages/util-crypto/src/blake2/asU8a.ts index 545ed747d..3c88ea5b9 100644 --- a/packages/util-crypto/src/blake2/asU8a.ts +++ b/packages/util-crypto/src/blake2/asU8a.ts @@ -24,8 +24,9 @@ import { blake2b, isReady } from '@polkadot/wasm-crypto'; */ export function blake2AsU8a (data: HexString | Uint8Array | string, bitLength = 256, key?: Uint8Array | null, onlyJs = false): Uint8Array { const byteLength = Math.ceil(bitLength / 8); + const u8a = u8aToU8a(data); return isReady() && !onlyJs - ? blake2b(u8aToU8a(data), u8aToU8a(key), byteLength) - : js.blake2b(u8aToU8a(data), key || undefined, byteLength); + ? blake2b(u8a, u8aToU8a(key), byteLength) + : js.blake2b(u8a, key || undefined, byteLength); } diff --git a/packages/util-crypto/src/crypto.ts b/packages/util-crypto/src/crypto.ts index 7f7f3eec7..698d0f0c4 100644 --- a/packages/util-crypto/src/crypto.ts +++ b/packages/util-crypto/src/crypto.ts @@ -3,9 +3,7 @@ import { isReady, waitReady } from '@polkadot/wasm-crypto'; -export function cryptoIsReady (): boolean { - return isReady(); -} +export const cryptoIsReady = isReady; export function cryptoWaitReady (): Promise { return waitReady() diff --git a/packages/util-crypto/src/hd/ledger/derivePrivate.ts b/packages/util-crypto/src/hd/ledger/derivePrivate.ts index 01629d7a0..69229af81 100644 --- a/packages/util-crypto/src/hd/ledger/derivePrivate.ts +++ b/packages/util-crypto/src/hd/ledger/derivePrivate.ts @@ -18,11 +18,15 @@ export function ledgerDerivePrivate (xprv: Uint8Array, index: number): Uint8Arra return u8aConcat( bnToU8a( - u8aToBn(kl, BN_LE_OPTS).iadd(u8aToBn(z.subarray(0, 28), BN_LE_OPTS).imul(BN_EIGHT)), + u8aToBn(kl, BN_LE_OPTS).iadd( + u8aToBn(z.subarray(0, 28), BN_LE_OPTS).imul(BN_EIGHT) + ), BN_LE_512_OPTS ).subarray(0, 32), bnToU8a( - u8aToBn(kr, BN_LE_OPTS).iadd(u8aToBn(z.subarray(32, 64), BN_LE_OPTS)), + u8aToBn(kr, BN_LE_OPTS).iadd( + u8aToBn(z.subarray(32, 64), BN_LE_OPTS) + ), BN_LE_512_OPTS ).subarray(0, 32), hmacSha512(cc, data).subarray(32, 64) diff --git a/packages/util-crypto/src/keccak/asU8a.ts b/packages/util-crypto/src/keccak/asU8a.ts index 8206870af..e88f69fe7 100644 --- a/packages/util-crypto/src/keccak/asU8a.ts +++ b/packages/util-crypto/src/keccak/asU8a.ts @@ -31,6 +31,8 @@ export function keccakAsU8a (value: HexString | Buffer | Uint8Array | string, bi ? keccak256(u8a) : keccak512(u8a) : new Uint8Array( - (is256 ? js.keccak256 : js.keccak512).update(u8a).arrayBuffer() + is256 + ? js.keccak256.update(u8a).arrayBuffer() + : js.keccak512.update(u8a).arrayBuffer() ); } diff --git a/packages/util-crypto/src/nacl/sign.spec.ts b/packages/util-crypto/src/nacl/sign.spec.ts index febe4b92d..e5dc90d84 100644 --- a/packages/util-crypto/src/nacl/sign.spec.ts +++ b/packages/util-crypto/src/nacl/sign.spec.ts @@ -4,8 +4,13 @@ import { stringToU8a } from '@polkadot/util'; import { waitReady } from '@polkadot/wasm-crypto'; +import { performanceTest } from '../../test/performance'; import { naclKeypairFromSeed, naclSign } from '.'; +const PAIR = naclKeypairFromSeed( + stringToU8a('12345678901234567890123456789012') +); + describe('naclSign', (): void => { beforeEach(async (): Promise => { await waitReady(); @@ -16,9 +21,7 @@ describe('naclSign', (): void => { expect( naclSign( new Uint8Array([0x61, 0x62, 0x63, 0x64]), - naclKeypairFromSeed( - stringToU8a('12345678901234567890123456789012') - ), + PAIR, onlyJs ) ).toEqual( @@ -26,4 +29,8 @@ describe('naclSign', (): void => { ); }); }); + + performanceTest('naclSign', 250, (input, onlyJs) => + naclSign(input, PAIR, onlyJs) + ); }); diff --git a/packages/util-crypto/src/pbkdf2/encode.ts b/packages/util-crypto/src/pbkdf2/encode.ts index 5bc9c94a6..3434dc600 100644 --- a/packages/util-crypto/src/pbkdf2/encode.ts +++ b/packages/util-crypto/src/pbkdf2/encode.ts @@ -18,9 +18,12 @@ interface Result { export function pbkdf2Encode (passphrase?: HexString | Buffer | Uint8Array | string, salt: Buffer | Uint8Array = randomAsU8a(), rounds = 2048, onlyJs = false): Result { const u8aPass = u8aToU8a(passphrase); const u8aSalt = u8aToU8a(salt); - const password = isReady() && !onlyJs - ? pbkdf2(u8aPass, u8aSalt, rounds) - : pbkdf2Sync(u8aPass, u8aSalt, rounds); - return { password, rounds, salt }; + return { + password: isReady() && !onlyJs + ? pbkdf2(u8aPass, u8aSalt, rounds) + : pbkdf2Sync(u8aPass, u8aSalt, rounds), + rounds, + salt + }; } diff --git a/packages/util-crypto/src/scrypt/encode.spec.ts b/packages/util-crypto/src/scrypt/encode.spec.ts new file mode 100644 index 000000000..da316047b --- /dev/null +++ b/packages/util-crypto/src/scrypt/encode.spec.ts @@ -0,0 +1,36 @@ +// Copyright 2017-2021 @polkadot/util-crypto authors & contributors +// SPDX-License-Identifier: Apache-2.0 + +import { waitReady } from '@polkadot/wasm-crypto'; + +import { performanceTest } from '../../test/performance'; +import { DEFAULT_PARAMS } from './defaults'; +import { scryptEncode } from '.'; + +export const KNOWN_TEST = 'testing, 123'; + +export const KNOWN_PASS = new Uint8Array([223, 185, 241, 135, 125, 17, 195, 27, 64, 64, 154, 69, 47, 82, 123, 38, 255, 230, 199, 200, 101, 115, 21, 116, 119, 59, 67, 43, 58, 220, 112, 70, 124, 139, 240, 206, 42, 148, 140, 132, 64, 226, 164, 25, 104, 80, 49, 92, 144, 132, 109, 178, 76, 225, 171, 116, 151, 181, 34, 243, 177, 235, 134, 76]); + +export const KNOWN_SALT = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8]); + +describe('scryptEncode', (): void => { + beforeEach(async (): Promise => { + await waitReady(); + }); + + describe.each([false, true])('onlyJs=%p', (onlyJs): void => { + it('generates a known output', (): void => { + expect( + scryptEncode(KNOWN_TEST, KNOWN_SALT, undefined, onlyJs) + ).toEqual({ + params: DEFAULT_PARAMS, + password: KNOWN_PASS, + salt: KNOWN_SALT + }); + }); + }); + + performanceTest('scryptEncode', 2, (input, onlyJs) => + scryptEncode(input, input, undefined, onlyJs) + ); +}); diff --git a/packages/util-crypto/src/scrypt/encode.ts b/packages/util-crypto/src/scrypt/encode.ts index 77ad28495..9cd3d3b53 100644 --- a/packages/util-crypto/src/scrypt/encode.ts +++ b/packages/util-crypto/src/scrypt/encode.ts @@ -18,11 +18,13 @@ interface Result { salt: Uint8Array; } -export function scryptEncode (passphrase?: HexString | Uint8Array | string, salt = randomAsU8a(), params = DEFAULT_PARAMS): Result { - const password = isReady() - ? scrypt(u8aToU8a(passphrase), salt, Math.log2(params.N), params.r, params.p) +export function scryptEncode (passphrase?: HexString | Uint8Array | string, salt = randomAsU8a(), params = DEFAULT_PARAMS, onlyJs = false): Result { + const u8a = u8aToU8a(passphrase); + + const password = isReady() && !onlyJs + ? scrypt(u8a, salt, Math.log2(params.N), params.r, params.p) : bufferToU8a( - scryptsy(u8aToBuffer(u8aToU8a(passphrase)), u8aToBuffer(salt), params.N, params.r, params.p, 64) + scryptsy(u8aToBuffer(u8a), u8aToBuffer(salt), params.N, params.r, params.p, 64) ); return { params, password, salt }; diff --git a/packages/util-crypto/src/xxhash/asU8a.spec.ts b/packages/util-crypto/src/xxhash/asU8a.spec.ts index c644d194e..2e12ed0a9 100644 --- a/packages/util-crypto/src/xxhash/asU8a.spec.ts +++ b/packages/util-crypto/src/xxhash/asU8a.spec.ts @@ -4,6 +4,7 @@ import { hexToU8a } from '@polkadot/util'; import { waitReady } from '@polkadot/wasm-crypto'; +import { performanceTest } from '../../test/performance'; import { xxhashAsU8a } from '.'; describe('xxhashAsU8a', (): void => { @@ -36,4 +37,8 @@ describe('xxhashAsU8a', (): void => { ); }); }); + + performanceTest('xxhashAsU8a', 8000, (input, onlyJs) => + xxhashAsU8a(input, 128, onlyJs) + ); }); diff --git a/packages/util-crypto/test/performance.ts b/packages/util-crypto/test/performance.ts index b9287701d..02926a135 100644 --- a/packages/util-crypto/test/performance.ts +++ b/packages/util-crypto/test/performance.ts @@ -1,7 +1,7 @@ // Copyright 2017-2021 @polkadot/util-crypto authors & contributors // SPDX-License-Identifier: Apache-2.0 -import { arrayRange, formatNumber } from '@polkadot/util'; +import { arrayRange } from '@polkadot/util'; import { randomAsU8a } from '@polkadot/util-crypto'; const GENERATED = arrayRange(64).map(() => randomAsU8a()); @@ -21,7 +21,7 @@ function perSecond (count: number, time: number): string { const ops = 1_000_000 / micro; return ` - ${formatNumber(ops).padStart(10)} ops/s + ${ops.toFixed(2).padStart(10)} ops/s ${micro.toFixed(2).padStart(10)} μs/op`; }