From 804ed13d0aa5f87ed2f80ae71116fb2d06c50a10 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Mon, 24 Feb 2020 11:55:15 +0100 Subject: [PATCH] Add signatureVerify (#552) * Add signatureVerify * addressOrPublicKey typo * Flatten verify, allow extra types * Add signatureVerify tests * De-dup address checksum checks --- CHANGELOG.md | 5 + packages/util-crypto/src/address/check.ts | 17 +--- .../util-crypto/src/address/checkChecksum.ts | 22 +++++ packages/util-crypto/src/address/decode.ts | 15 +-- packages/util-crypto/src/address/index.ts | 2 + packages/util-crypto/src/index.ts | 1 + packages/util-crypto/src/signature/index.ts | 9 ++ .../util-crypto/src/signature/verify.spec.ts | 92 +++++++++++++++++++ packages/util-crypto/src/signature/verify.ts | 67 ++++++++++++++ packages/util-crypto/src/types.ts | 5 + packages/util/src/u8a/fixLength.ts | 4 +- packages/util/src/u8a/toBuffer.ts | 8 +- packages/util/src/u8a/toString.ts | 8 +- packages/util/src/u8a/toU8a.ts | 16 +--- 14 files changed, 221 insertions(+), 50 deletions(-) create mode 100644 packages/util-crypto/src/address/checkChecksum.ts create mode 100644 packages/util-crypto/src/signature/index.ts create mode 100644 packages/util-crypto/src/signature/verify.spec.ts create mode 100644 packages/util-crypto/src/signature/verify.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 67ef35949..3fb31cb13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +# 2.6.0-beta.x + +- Add `signatureVerify (message: Uint8Array | string, signature: Uint8Array | string, addressOrPublicKey: Uint8Array | string): VerifyResult` to verify any signature, regardless of type. Returns validity & detected crypto type. +- Add `addressCheckChecksum (decoded: Uint8Array)` as an helper to extract and verify the ss58 checksum + # 2.5.1 Feb 22, 2020 - **Breaking change** (TypeScript only) The `*.d.ts` files now contain TypeScript 3.8 features, `#private`, which is not usable in older versions diff --git a/packages/util-crypto/src/address/check.ts b/packages/util-crypto/src/address/check.ts index 50053f6fa..aa59b26f6 100644 --- a/packages/util-crypto/src/address/check.ts +++ b/packages/util-crypto/src/address/check.ts @@ -6,8 +6,8 @@ import { Prefix } from './types'; import bs58 from 'bs58'; +import checkChecksum from './checkChecksum'; import defaults from './defaults'; -import sshash from './sshash'; export default function check (address: string, prefix: Prefix): [boolean, string | null] { const decoded = bs58.decode(address); @@ -18,18 +18,7 @@ export default function check (address: string, prefix: Prefix): [boolean, strin return [false, 'Invalid decoded address length']; } - const isPublicKey = decoded.length === 35; + const [isValid] = checkChecksum(decoded); - // non-publicKeys has 1 byte checksums, else default to 2 - const endPos = decoded.length - (isPublicKey ? 2 : 1); - - // calculate the hash and do the checksum byte checks - const hash = sshash(decoded.subarray(0, endPos)); - const checks = isPublicKey - ? decoded[decoded.length - 2] === hash[0] && decoded[decoded.length - 1] === hash[1] - : decoded[decoded.length - 1] === hash[0]; - - return !checks - ? [false, 'Invalid decoded address checksum'] - : [true, null]; + return [isValid, isValid ? null : 'Invalid decoded address checksum']; } diff --git a/packages/util-crypto/src/address/checkChecksum.ts b/packages/util-crypto/src/address/checkChecksum.ts new file mode 100644 index 000000000..b5c52353d --- /dev/null +++ b/packages/util-crypto/src/address/checkChecksum.ts @@ -0,0 +1,22 @@ +// Copyright 2017-2020 @polkadot/util-crypto 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 sshash from './sshash'; + +export default function checkChecksum (decoded: Uint8Array): [boolean, number] { + const isPublicKey = decoded.length === 35; + + // non-publicKeys has 1 byte checksums, else default to 2 + const length = decoded.length - (isPublicKey ? 2 : 1); + + // calculate the hash and do the checksum byte checks + const hash = sshash(decoded.subarray(0, length)); + + // see if the hash actually matches + const isValid = isPublicKey + ? decoded[decoded.length - 2] === hash[0] && decoded[decoded.length - 1] === hash[1] + : decoded[decoded.length - 1] === hash[0]; + + return [isValid, length]; +} diff --git a/packages/util-crypto/src/address/decode.ts b/packages/util-crypto/src/address/decode.ts index bb660311e..12d964ccc 100644 --- a/packages/util-crypto/src/address/decode.ts +++ b/packages/util-crypto/src/address/decode.ts @@ -9,8 +9,8 @@ import { Prefix } from './types'; import bs58 from 'bs58'; import { assert, bufferToU8a, isHex, isU8a, u8aToU8a } from '@polkadot/util'; +import checkChecksum from './checkChecksum'; import defaults from './defaults'; -import sshash from './sshash'; // eslint-disable-next-line @typescript-eslint/no-unused-vars export default function decode (encoded: string | Uint8Array, ignoreChecksum?: boolean, ss58Format: Prefix = 99): Uint8Array { @@ -30,18 +30,9 @@ export default function decode (encoded: string | Uint8Array, ignoreChecksum?: b // console.log(`WARN: Expected ${prefix}, found ${decoded[0]}`); // } - const isPublicKey = decoded.length === 35; + const [isValid, endPos] = checkChecksum(decoded); - // non-publicKeys has 1 byte checksums, else default to 2 - const endPos = decoded.length - (isPublicKey ? 2 : 1); - - // calculate the hash and do the checksum byte checks - const hash = sshash(decoded.subarray(0, endPos)); - const checks = isPublicKey - ? decoded[decoded.length - 2] === hash[0] && decoded[decoded.length - 1] === hash[1] - : decoded[decoded.length - 1] === hash[0]; - - assert(ignoreChecksum || checks, error('Invalid decoded address checksum')); + assert(ignoreChecksum || isValid, error('Invalid decoded address checksum')); return decoded.slice(1, endPos); } diff --git a/packages/util-crypto/src/address/index.ts b/packages/util-crypto/src/address/index.ts index a7c45c3a2..92325cfc8 100644 --- a/packages/util-crypto/src/address/index.ts +++ b/packages/util-crypto/src/address/index.ts @@ -3,12 +3,14 @@ // of the Apache-2.0 license. See the LICENSE file for details. import checkAddress from './check'; +import checkAddressChecksum from './checkChecksum'; import decodeAddress from './decode'; import encodeAddress from './encode'; import setSS58Format from './setSS58Format'; export { checkAddress, + checkAddressChecksum, decodeAddress, encodeAddress, setSS58Format diff --git a/packages/util-crypto/src/index.ts b/packages/util-crypto/src/index.ts index 1ae1175ce..08b615a93 100644 --- a/packages/util-crypto/src/index.ts +++ b/packages/util-crypto/src/index.ts @@ -16,6 +16,7 @@ export * from './random'; export * from './schnorrkel'; export * from './secp256k1'; export * from './sha512'; +export * from './signature'; export * from './xxhash'; export function cryptoWaitReady (): Promise { diff --git a/packages/util-crypto/src/signature/index.ts b/packages/util-crypto/src/signature/index.ts new file mode 100644 index 000000000..7fa5fd2f8 --- /dev/null +++ b/packages/util-crypto/src/signature/index.ts @@ -0,0 +1,9 @@ +// Copyright 2017-2020 @polkadot/util-crypto authors & contributors +// This software may be modified and distributed under the terms +// of the Apache-2.0 license. See the LICENSE file for details. + +/** + * @summary Utilities for working with signatures + */ + +export { default as signatureVerify } from './verify'; diff --git a/packages/util-crypto/src/signature/verify.spec.ts b/packages/util-crypto/src/signature/verify.spec.ts new file mode 100644 index 000000000..28e3dbc65 --- /dev/null +++ b/packages/util-crypto/src/signature/verify.spec.ts @@ -0,0 +1,92 @@ +// Copyright 2017-2020 @polkadot/util-crypto 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 { hexToU8a, stringToU8a, u8aConcat, u8aToHex } from '@polkadot/util'; +import { waitReady } from '@polkadot/wasm-crypto'; + +import { decodeAddress } from '../address'; +import { signatureVerify } from '.'; + +const ADDR_ED = 'DxN4uvzwPzJLtn17yew6jEffPhXQfdKHTp2brufb98vGbPN'; +const ADDR_SR = 'EK1bFgKm2FsghcttHT7TB7rNyXApFgs9fCbijMGQNyFGBQm'; +const MESSAGE = 'hello world'; +const SIG_ED = '0x299d3bf4c8bb51af732f8067b3a3015c0862a5ff34721749d8ed6577ea2708365d1c5f76bd519009971e41156f12c70abc2533837ceb3bad9a05a99ab923de06'; +const SIG_SR = '0xca01419b5a17219f7b78335658cab3b126db523a5df7be4bfc2bef76c2eb3b1dcf4ca86eb877d0a6cf6df12db5995c51d13b00e005d053b892bd09c594434288'; +const MUL_ED = u8aToHex(u8aConcat(new Uint8Array([0]), hexToU8a(SIG_ED))); +const MUL_SR = u8aToHex(u8aConcat(new Uint8Array([1]), hexToU8a(SIG_SR))); + +describe('signatureVerify', (): void => { + beforeEach(async (): Promise => { + await waitReady(); + }); + + it('throws on invalid signature length', (): void => { + expect( + () => signatureVerify(MESSAGE, new Uint8Array(32), ADDR_ED) + ).toThrow('Invalid signature length, expected 64 or 65 bytes, found 32'); + }); + + describe('verifyDetect', (): void => { + it('verifies an ed25519 signature', (): void => { + expect(signatureVerify(MESSAGE, SIG_ED, ADDR_ED)).toEqual({ + crypto: 'ed25519', + isValid: true + }); + }); + + it('verifies an sr25519 signature', (): void => { + expect(signatureVerify(MESSAGE, SIG_SR, ADDR_SR)).toEqual({ + crypto: 'sr25519', + isValid: true + }); + }); + + it('allows various inputs', (): void => { + expect(signatureVerify(stringToU8a(MESSAGE), hexToU8a(SIG_ED), decodeAddress(ADDR_ED))).toEqual({ + crypto: 'ed25519', + isValid: true + }); + }); + + it('fails on an invalid signature', (): void => { + expect(signatureVerify(MESSAGE, SIG_SR, ADDR_ED)).toEqual({ + crypto: 'none', + isValid: false + }); + }); + }); + + describe('verifyMultisig', (): void => { + it('throws with invalid multisig indicator', (): void => { + const u8aSig = hexToU8a(MUL_ED); + + u8aSig[0] = 69; + + expect( + () => signatureVerify(MESSAGE, u8aSig, ADDR_ED) + ).toThrow('Unknown crypto type, expected signature prefix of 0 or 1, found 69'); + }); + + it('verifies an ed25519 signature', (): void => { + expect(signatureVerify(MESSAGE, MUL_ED, ADDR_ED)).toEqual({ + crypto: 'ed25519', + isValid: true + }); + }); + + it('verifies an sr25519 signature', (): void => { + expect(signatureVerify(MESSAGE, MUL_SR, ADDR_SR)).toEqual({ + crypto: 'sr25519', + isValid: true + }); + }); + + it('fails on an invalid signature', (): void => { + expect(signatureVerify(MESSAGE, MUL_SR, ADDR_ED)).toEqual({ + crypto: 'sr25519', + isValid: false + }); + }); + }); +}); diff --git a/packages/util-crypto/src/signature/verify.ts b/packages/util-crypto/src/signature/verify.ts new file mode 100644 index 000000000..59736c0df --- /dev/null +++ b/packages/util-crypto/src/signature/verify.ts @@ -0,0 +1,67 @@ +// Copyright 2017-2020 @polkadot/util-crypto 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 { KeypairType, VerifyResult } from '../types'; + +import { assert, u8aToU8a } from '@polkadot/util'; + +import addressDecode from '../address/decode'; +import naclVerify from '../nacl/verify'; +import schnorrkelVerify from '../schnorrkel/verify'; + +const VERIFIERS: [KeypairType, (message: Uint8Array | string, signature: Uint8Array | string, publicKey: Uint8Array | string) => boolean][] = [ + ['ed25519', naclVerify], + ['sr25519', schnorrkelVerify] +]; + +function verifyDetect (result: VerifyResult, message: Uint8Array | string, signature: Uint8Array, publicKey: Uint8Array): VerifyResult { + result.isValid = VERIFIERS.some(([crypto, verify]): boolean => { + try { + if (verify(message, signature, publicKey)) { + result.crypto = crypto; + + return true; + } + } catch (error) { + // do nothing, result.isValid still set to false + } + + return false; + }); + + return result; +} + +function verifyMultisig (result: VerifyResult, message: Uint8Array | string, signature: Uint8Array, publicKey: Uint8Array): VerifyResult { + assert([0, 1].includes(signature[0]), `Unknown crypto type, expected signature prefix of 0 or 1, found ${signature[0]}`); + + const isEd25519 = signature[0] === 0; + + result.crypto = isEd25519 + ? 'ed25519' + : 'sr25519'; + + try { + result.isValid = isEd25519 + ? naclVerify(message, signature.subarray(1), publicKey) + : schnorrkelVerify(message, signature.subarray(1), publicKey); + } catch (error) { + // ignore, result.isValid still set to false + } + + return result; +} + +export default function signatureVerify (message: Uint8Array | string, signature: Uint8Array | string, addressOrPublicKey: Uint8Array | string): VerifyResult { + const signatureU8a = u8aToU8a(signature); + + assert([64, 65].includes(signatureU8a.length), `Invalid signature length, expected 64 or 65 bytes, found ${signatureU8a.length}`); + + const result: VerifyResult = { crypto: 'none', isValid: false }; + const publicKey = addressDecode(addressOrPublicKey); + + return signatureU8a.length === 65 + ? verifyMultisig(result, message, signatureU8a, publicKey) + : verifyDetect(result, message, signatureU8a, publicKey); +} diff --git a/packages/util-crypto/src/types.ts b/packages/util-crypto/src/types.ts index e49c54374..396e1cba3 100644 --- a/packages/util-crypto/src/types.ts +++ b/packages/util-crypto/src/types.ts @@ -13,3 +13,8 @@ export interface Seedpair { } export type KeypairType = 'ed25519' | 'sr25519'; + +export interface VerifyResult { + crypto: 'none' | KeypairType; + isValid: boolean; +} diff --git a/packages/util/src/u8a/fixLength.ts b/packages/util/src/u8a/fixLength.ts index cb5d8d1c0..723ff7032 100644 --- a/packages/util/src/u8a/fixLength.ts +++ b/packages/util/src/u8a/fixLength.ts @@ -23,9 +23,7 @@ export default function u8aFixLength (value: Uint8Array, bitLength = -1, atStart if (bitLength === -1 || value.length === byteLength) { return value; - } - - if (value.length > byteLength) { + } else if (value.length > byteLength) { return value.subarray(0, byteLength); } diff --git a/packages/util/src/u8a/toBuffer.ts b/packages/util/src/u8a/toBuffer.ts index c88788e06..fd2ee0ee3 100644 --- a/packages/util/src/u8a/toBuffer.ts +++ b/packages/util/src/u8a/toBuffer.ts @@ -17,9 +17,7 @@ * ``` */ export default function u8aToBuffer (value?: Uint8Array | null): Buffer { - if (!value) { - return Buffer.from([]); - } - - return Buffer.from(value); + return !value + ? Buffer.from([]) + : Buffer.from(value); } diff --git a/packages/util/src/u8a/toString.ts b/packages/util/src/u8a/toString.ts index 0a6887cc1..1b4182b1d 100644 --- a/packages/util/src/u8a/toString.ts +++ b/packages/util/src/u8a/toString.ts @@ -33,9 +33,7 @@ try { * ``` */ export default function u8aToString (value?: Uint8Array | null): string { - if (!value || !value.length) { - return ''; - } - - return decoder.decode(value); + return !value?.length + ? '' + : decoder.decode(value); } diff --git a/packages/util/src/u8a/toU8a.ts b/packages/util/src/u8a/toU8a.ts index 90fd14731..ff48a603c 100644 --- a/packages/util/src/u8a/toU8a.ts +++ b/packages/util/src/u8a/toU8a.ts @@ -27,21 +27,15 @@ import stringToU8a from '../string/toU8a'; export default function u8aToU8a (value?: number[] | Buffer | Uint8Array | string | null): Uint8Array { if (!value) { return new Uint8Array(); - } - - if (isBuffer(value)) { + } else if (isBuffer(value)) { return bufferToU8a(value); - } - - if (isString(value)) { + } else if (isString(value)) { return isHex(value) ? hexToU8a(value) : stringToU8a(value); } - if (Array.isArray(value)) { - return Uint8Array.from(value); - } - - return value; + return Array.isArray(value) + ? Uint8Array.from(value) + : value; }