Use secp256k1 from wasm (#1276)

* Use secp256k1 from wasm

* Expand & recover

* sign (tests failing)

* Pass onlyJs flags everywhere

* Adjust, all ready to actually pass... they don't

* naming

* Fix verify tests

* Adjust verify with non-hashing

* bump wasm

* Allow verify against address or publicKey

* Passing tests

* comment for wasm

* bi/bn versions for tweakadd

* Bumps

* Adjust
This commit is contained in:
Jaco
2021-12-03 16:23:41 +02:00
committed by GitHub
parent 7bfca0d40f
commit 303a57c4b5
19 changed files with 362 additions and 148 deletions
+1
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
export const BN_BE_OPTS = { isLe: false };
export const BN_LE_OPTS = { isLe: true };
export const BN_LE_16_OPTS = { bitLength: 16, isLe: true };
@@ -2,17 +2,43 @@
// SPDX-License-Identifier: Apache-2.0
import { hexToU8a } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { secp256k1Compress } from './';
import { performanceWasm } from '../../test/performance';
import { secp256k1Compress } from '.';
describe('secp256k1Compress', (): void => {
it('compresses a known key', (): void => {
expect(
secp256k1Compress(
hexToU8a('0x04b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af')
)
).toEqual(
hexToU8a('0x03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077')
);
beforeEach(async (): Promise<void> => {
await waitReady();
});
describe.each([false, true])('onlyJs=%p', (onlyJs): void => {
it('returns a compressed key as-is', (): void => {
expect(
secp256k1Compress(
hexToU8a('0x03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077'),
onlyJs
)
).toEqual(
hexToU8a('0x03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077')
);
});
it('compresses a known key', (): void => {
expect(
secp256k1Compress(
hexToU8a('0x04b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af'),
onlyJs
)
).toEqual(
hexToU8a('0x03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077')
);
});
});
performanceWasm('secp256k1Compress', 100000, (input, onlyJs) => secp256k1Compress(input, onlyJs),
[[
hexToU8a('0x04b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af')
]]
);
});
+15 -8
View File
@@ -2,16 +2,23 @@
// SPDX-License-Identifier: Apache-2.0
import { assert } from '@polkadot/util';
import { isReady, secp256k1Compress as wasm } from '@polkadot/wasm-crypto';
import { secp256k1 } from './secp256k1';
export function secp256k1Compress (publicKey: Uint8Array): Uint8Array {
assert([33, 65].includes(publicKey.length), 'Invalid publicKey provided');
export function secp256k1Compress (publicKey: Uint8Array, onlyJs?: boolean): Uint8Array {
if (publicKey.length === 33) {
return publicKey;
}
return new Uint8Array(
secp256k1
.keyFromPublic(publicKey)
.getPublic()
.encodeCompressed()
);
assert(publicKey.length === 65, 'Invalid publicKey provided');
return !onlyJs && isReady()
? wasm(publicKey)
: new Uint8Array(
secp256k1
.keyFromPublic(publicKey)
.getPublic()
.encodeCompressed()
);
}
@@ -2,27 +2,43 @@
// SPDX-License-Identifier: Apache-2.0
import { hexToU8a } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { secp256k1Expand } from './';
import { performanceWasm } from '../../test/performance';
import { secp256k1Expand } from '.';
describe('secp256k1Expand', (): void => {
it('expands a known key', (): void => {
expect(
secp256k1Expand(
hexToU8a('0x03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077')
)
).toEqual(
hexToU8a('0xb9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af')
);
beforeEach(async (): Promise<void> => {
await waitReady();
});
it('expands a known full key', (): void => {
expect(
secp256k1Expand(
hexToU8a('0x04b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af')
)
).toEqual(
hexToU8a('0xb9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af')
);
describe.each([false, true])('onlyJs=%p', (onlyJs): void => {
it('expands a known key', (): void => {
expect(
secp256k1Expand(
hexToU8a('0x03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077'),
onlyJs
)
).toEqual(
hexToU8a('0xb9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af')
);
});
it('expands a known full key', (): void => {
expect(
secp256k1Expand(
hexToU8a('0x04b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af'),
onlyJs
)
).toEqual(
hexToU8a('0xb9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb1307763fe926c273235fd979a134076d00fd1683cbd35868cb485d4a3a640e52184af')
);
});
});
performanceWasm('secp256k1Expand', 2000, (input, onlyJs) => secp256k1Expand(input, onlyJs),
[[
hexToU8a('0x03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077')
]]
);
});
+11 -2
View File
@@ -2,12 +2,21 @@
// SPDX-License-Identifier: Apache-2.0
import { assert, bnToU8a, u8aConcat } from '@polkadot/util';
import { isReady, secp256k1Expand as wasm } from '@polkadot/wasm-crypto';
import { BN_BE_256_OPTS } from '../bn';
import { secp256k1 } from './secp256k1';
export function secp256k1Expand (publicKey: Uint8Array): Uint8Array {
assert([33, 65].includes(publicKey.length), 'Invalid publicKey provided');
export function secp256k1Expand (publicKey: Uint8Array, onlyJs?: boolean): Uint8Array {
if (publicKey.length === 65) {
return publicKey.subarray(1);
}
assert(publicKey.length === 33, 'Invalid publicKey provided');
if (!onlyJs && isReady()) {
return wasm(publicKey).subarray(1);
}
const expanded = secp256k1
.keyFromPublic(publicKey)
@@ -4,12 +4,6 @@
import { secp256k1Hasher } from './hasher';
describe('secp256k1Hasher', (): void => {
it('fails with unknown hasher', (): void => {
expect(
() => secp256k1Hasher('unknown' as 'blake2', 'testing')
).toThrow(/Unsupported secp256k1 hasher 'unknown', expected one of blake2, keccak/);
});
it('creates a blake2 hash', (): void => {
expect(
secp256k1Hasher('blake2', 'abc')
+4 -10
View File
@@ -6,14 +6,8 @@ import type { HashType } from './types';
import { blake2AsU8a } from '../blake2';
import { keccakAsU8a } from '../keccak';
const HASH_TYPES = ['blake2', 'keccak'];
export function secp256k1Hasher (hashType: HashType, data: Uint8Array | string): Uint8Array {
if (hashType === 'blake2') {
return blake2AsU8a(data);
} else if (hashType === 'keccak') {
return keccakAsU8a(data);
}
throw new Error(`Unsupported secp256k1 hasher '${hashType as string}', expected one of ${HASH_TYPES.join(', ')}`);
export function secp256k1Hasher (hashType: HashType, data: Uint8Array | string, onlyJs?: boolean): Uint8Array {
return hashType === 'keccak'
? keccakAsU8a(data, undefined, onlyJs)
: blake2AsU8a(data, undefined, undefined, onlyJs);
}
@@ -2,7 +2,9 @@
// SPDX-License-Identifier: Apache-2.0
import { hexToU8a, u8aToHex } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { performanceWasm } from '../../../test/performance';
import { mnemonicToMiniSecret } from '../../mnemonic';
import { secp256k1PairFromSeed } from '..';
@@ -37,23 +39,33 @@ const tests: Test[] = [
];
describe('secp256k1PairFromSeed', (): void => {
beforeEach(async (): Promise<void> => {
await waitReady();
});
const TEST = hexToU8a('0x4380de832af797688026ce24f85204d508243f201650c1a134929e5458b7fbae');
const RESULT = {
publicKey: hexToU8a('0x03fd8c74f795ced92064b86191cb2772b1e3a0947740aa0a5a6e379592471fd85b'),
secretKey: hexToU8a('0x4380de832af797688026ce24f85204d508243f201650c1a134929e5458b7fbae')
};
it('generates a valid publicKey/secretKey pair (u8a)', (): void => {
expect(secp256k1PairFromSeed(TEST)).toEqual(RESULT);
});
describe.each([false, true])('onlyJs=%p', (onlyJs): void => {
it('generates a valid publicKey/secretKey pair (u8a)', (): void => {
expect(secp256k1PairFromSeed(TEST, onlyJs)).toEqual(RESULT);
});
tests.forEach(([mnemonic, secretKey, publicKey], index): void => {
it(`creates valid against known (${index})`, (): void => {
const seed = mnemonicToMiniSecret(mnemonic);
const pair = secp256k1PairFromSeed(seed);
tests.forEach(([mnemonic, secretKey, publicKey], index): void => {
it(`creates valid against known (${index})`, (): void => {
const seed = mnemonicToMiniSecret(mnemonic);
const pair = secp256k1PairFromSeed(seed, onlyJs);
expect(u8aToHex(pair.secretKey)).toEqual(secretKey);
expect(u8aToHex(pair.publicKey)).toEqual(publicKey);
expect(u8aToHex(pair.secretKey)).toEqual(secretKey);
expect(u8aToHex(pair.publicKey)).toEqual(publicKey);
});
});
});
performanceWasm('secp256k1PairFromSeed', 500, (input, onlyJs) =>
secp256k1PairFromSeed(input, onlyJs)
);
});
@@ -4,6 +4,7 @@
import type { Keypair } from '../../types';
import { assert, bnToU8a } from '@polkadot/util';
import { isReady, secp256k1FromSeed } from '@polkadot/wasm-crypto';
import { BN_BE_256_OPTS } from '../../bn';
import { secp256k1 } from '../secp256k1';
@@ -12,9 +13,18 @@ import { secp256k1 } from '../secp256k1';
* @name secp256k1PairFromSeed
* @description Returns a object containing a `publicKey` & `secretKey` generated from the supplied seed.
*/
export function secp256k1PairFromSeed (seed: Uint8Array): Keypair {
export function secp256k1PairFromSeed (seed: Uint8Array, onlyJs?: boolean): Keypair {
assert(seed.length === 32, 'Expected valid 32-byte private key as a seed');
if (!onlyJs && isReady()) {
const full = secp256k1FromSeed(seed);
return {
publicKey: full.slice(32),
secretKey: full.slice(0, 32)
};
}
const key = secp256k1.keyFromPrivate(seed);
return {
@@ -2,17 +2,30 @@
// SPDX-License-Identifier: Apache-2.0
import { u8aToHex, u8aToU8a } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { performanceWasm } from '../../test/performance';
import { keccakAsU8a } from '../keccak';
import { secp256k1Recover } from '.';
describe('secp256k1Recover', (): void => {
it('recovers a publicKey', (): void => {
const pubKey = '0x93a9fc7154c6da3c826415df01eb0e37fb4da4b0';
const sig = '0x7505f2880114da51b3f5d535f8687953c0ab9af4ab81e592eaebebf53b728d2b6dfd9b5bcd70fee412b1f31360e7c2774009305cb84fc50c1d0ff8034dfa5fff';
const msg = '0xa30b64ce1eedf409c8afb801d72c05234e64849ea538c15dd3c8cf4ffcf166c9';
const res = keccakAsU8a(secp256k1Recover(u8aToU8a(msg), u8aToU8a(sig), 0));
const sig = u8aToU8a('0x7505f2880114da51b3f5d535f8687953c0ab9af4ab81e592eaebebf53b728d2b6dfd9b5bcd70fee412b1f31360e7c2774009305cb84fc50c1d0ff8034dfa5fff');
const msg = u8aToU8a('0xa30b64ce1eedf409c8afb801d72c05234e64849ea538c15dd3c8cf4ffcf166c9');
expect(u8aToHex(res.subarray(12))).toEqual(pubKey);
describe('secp256k1Recover', (): void => {
beforeEach(async (): Promise<void> => {
await waitReady();
});
describe.each([false, true])('onlyJs=%p', (onlyJs): void => {
it('recovers a publicKey', (): void => {
const pubKey = '0x93a9fc7154c6da3c826415df01eb0e37fb4da4b0';
const res = keccakAsU8a(secp256k1Recover(msg, sig, 0, undefined, onlyJs));
expect(u8aToHex(res.subarray(-20))).toEqual(pubKey);
});
});
performanceWasm('secp256k1Recover', 200, (_, onlyJs) =>
secp256k1Recover(msg, sig, 0, undefined, onlyJs)
);
});
+22 -7
View File
@@ -1,17 +1,32 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HashType } from './types';
import { assert } from '@polkadot/util';
import { isReady, secp256k1Recover as wasm } from '@polkadot/wasm-crypto';
import { secp256k1Compress } from './compress';
import { secp256k1Expand } from './expand';
import { secp256k1 } from './secp256k1';
/**
* @name secp256k1Recover
* @description Recovers a publicKey from the supplied signature
*/
export function secp256k1Recover (message: Uint8Array, signature: Uint8Array, recovery: number): Uint8Array {
return new Uint8Array(
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-argument
secp256k1
.recoverPubKey(message, { r: signature.slice(0, 32), s: signature.slice(32, 64) }, recovery)
.encode(null, true)
);
export function secp256k1Recover (message: Uint8Array, signature: Uint8Array, recovery: number, hashType: HashType = 'blake2', onlyJs?: boolean): Uint8Array {
const publicKey = !onlyJs && isReady()
? wasm(message, signature.slice(0, 64), recovery)
: new Uint8Array(
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-argument
secp256k1
.recoverPubKey(message, { r: signature.slice(0, 32), s: signature.slice(32, 64) }, recovery)
.encode(null, true)
);
assert(publicKey, 'Unable to recover publicKey from signature');
return hashType === 'keccak'
? secp256k1Expand(publicKey, onlyJs)
: secp256k1Compress(publicKey, onlyJs);
}
@@ -0,0 +1,38 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { hexToU8a } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { performanceWasm } from '../../test/performance';
import { secp256k1PairFromSeed, secp256k1Recover, secp256k1Sign } from '.';
const pair = secp256k1PairFromSeed(hexToU8a('0x4380de832af797688026ce24f85204d508243f201650c1a134929e5458b7fbae'));
const msg = hexToU8a('0xa30b64ce1eedf409c8afb801d72c05234e64849ea538c15dd3c8cf4ffcf166c9');
describe('sign', (): void => {
beforeEach(async (): Promise<void> => {
await waitReady();
});
describe.each([false, true])('onlyJs=%p', (onlyJs): void => {
it('generates a known signature', (): void => {
expect(
secp256k1Sign(msg, pair, undefined, onlyJs)
).toEqual(hexToU8a(
// as of libsecp256k1 0.7.0 the wasm yields different s & v values
onlyJs
? '0xdf92f73d9f060cefacf187b5414491cb992998ace017fa48839b5cda3e264ba8c4efa521361678d9b8582744d77aa4b8d886d7380b7808a683174afad9c4700300'
: '0xdf92f73d9f060cefacf187b5414491cb992998ace017fa48839b5cda3e264ba83b105adec9e9872647a7d8bb28855b45e22805aea3d097953cbb1391f671d13e01'
));
});
});
// since the libsecp256k1 signatures don't match (but can be verified), we
// do both signing and verification here (checking the extracted key)
performanceWasm('secp256k1Sign/Verify', 100, (_, onlyJs) => {
const sig = secp256k1Sign(msg, pair, undefined, onlyJs);
return secp256k1Recover(msg, sig, sig[64], undefined, onlyJs);
});
});
+9 -2
View File
@@ -5,6 +5,7 @@ import type { Keypair } from '../types';
import type { HashType } from './types';
import { assert, bnToU8a, u8aConcat } from '@polkadot/util';
import { isReady, secp256k1Sign as wasm } from '@polkadot/wasm-crypto';
import { BN_BE_256_OPTS } from '../bn';
import { secp256k1Hasher } from './hasher';
@@ -14,11 +15,17 @@ import { secp256k1 } from './secp256k1';
* @name secp256k1Sign
* @description Returns message signature of `message`, using the supplied pair
*/
export function secp256k1Sign (message: Uint8Array | string, { secretKey }: Partial<Keypair>, hashType: HashType = 'blake2'): Uint8Array {
export function secp256k1Sign (message: Uint8Array | string, { secretKey }: Partial<Keypair>, hashType: HashType = 'blake2', onlyJs?: boolean): Uint8Array {
assert(secretKey?.length === 32, 'Expected valid secp256k1 secretKey, 32-bytes');
const data = secp256k1Hasher(hashType, message, onlyJs);
if (!onlyJs && isReady()) {
return wasm(data, secretKey);
}
const key = secp256k1.keyFromPrivate(secretKey);
const ecsig = key.sign(secp256k1Hasher(hashType, message));
const ecsig = key.sign(data);
return u8aConcat(
bnToU8a(ecsig.r, BN_BE_256_OPTS),
@@ -15,7 +15,7 @@ describe('sign and verify', (): void => {
const sig = '0x92fcacf0946bbd10b31dfe16d567ed1d3014e81007dd9e5256e19c0f07eacc1643b151ca29e449a765e16a7ce59b88d800467d6b3412d30ea8ad22307a59664b00';
const msg = stringToU8a('secp256k1');
expect(secp256k1Verify(msg, sig, address)).toBe(true);
expect(secp256k1Verify(msg, sig, address)).toEqual(true);
});
it('has 65-byte signatures', (): void => {
@@ -29,7 +29,7 @@ describe('sign and verify', (): void => {
const signature = secp256k1Sign(MESSAGE, pair);
const address = secp256k1Hasher('blake2', pair.publicKey);
expect(secp256k1Verify(MESSAGE, signature, address)).toBe(true);
expect(secp256k1Verify(MESSAGE, signature, address)).toEqual(true);
});
it('signs/verifies a message by random key (keccak)', (): void => {
@@ -37,7 +37,7 @@ describe('sign and verify', (): void => {
const signature = secp256k1Sign(MESSAGE, pair, 'keccak');
const address = secp256k1Hasher('keccak', secp256k1Expand(pair.publicKey));
expect(secp256k1Verify(MESSAGE, signature, address, 'keccak')).toBe(true);
expect(secp256k1Verify(MESSAGE, signature, address, 'keccak')).toEqual(true);
});
it('fails verification on hasher mismatches', (): void => {
@@ -45,7 +45,7 @@ describe('sign and verify', (): void => {
const signature = secp256k1Sign(MESSAGE, pair, 'keccak');
const address = secp256k1Hasher('keccak', secp256k1Expand(pair.publicKey));
expect(secp256k1Verify(MESSAGE, signature, address, 'blake2')).toBe(false);
expect(secp256k1Verify(MESSAGE, signature, address, 'blake2')).toEqual(false);
});
it('works over a range of random keys (blake2)', (): void => {
@@ -60,7 +60,7 @@ describe('sign and verify', (): void => {
secp256k1Hasher('blake2', pair.publicKey),
'blake2'
)
).toBe(true);
).toEqual(true);
} catch (error) {
console.error(`blake2 failed on #${i}`);
throw error;
@@ -80,7 +80,7 @@ describe('sign and verify', (): void => {
secp256k1Hasher('keccak', secp256k1Expand(pair.publicKey)),
'keccak'
)
).toBe(true);
).toEqual(true);
} catch (error) {
console.error(`keccak failed on #${i}`);
throw error;
@@ -4,13 +4,22 @@
import { secp256k1PrivateKeyTweakAdd } from './tweakAdd';
describe('TweakAdd', (): void => {
describe('PrivateKey TweakAdd', (): void => {
it('fails for wrong array length', (): void => {
const A = new Uint8Array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]);
const B = new Uint8Array([3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]);
expect(
() => secp256k1PrivateKeyTweakAdd(A, B)
).toThrow(/Expected tweak to be an Uint8Array/);
});
describe.each([false, true])('onlyBn=%p', (onlyBn): void => {
it('succeeds for a simple case', (): void => {
const A = new Uint8Array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]);
const B = new Uint8Array([3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]);
expect(
secp256k1PrivateKeyTweakAdd(A, B)
secp256k1PrivateKeyTweakAdd(A, B, onlyBn)
).toEqual(new Uint8Array([
3, 4, 3, 4, 3, 4, 3, 4, 3,
4, 3, 4, 3, 4, 3, 4, 3, 4,
@@ -18,14 +27,5 @@ describe('TweakAdd', (): void => {
4, 3, 4, 3, 4
]));
});
it('fails for wrong array length', (): void => {
const A = new Uint8Array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]);
const B = new Uint8Array([3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]);
expect(
() => secp256k1PrivateKeyTweakAdd(A, B)
).toThrow(/Expected tweak to be an Uint8Array/);
});
});
});
+42 -20
View File
@@ -1,32 +1,54 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { assert, BN, bnToU8a, isU8a } from '@polkadot/util';
import { _0n, assert, BN, bnToU8a, hasBigInt, isU8a, nToU8a, u8aToBigInt } from '@polkadot/util';
import { BigInt } from '@polkadot/x-bigint';
import { BN_BE_256_OPTS } from '../bn';
import { BN_BE_256_OPTS, BN_BE_OPTS } from '../bn';
// pre-defined curve param as lifted form elliptic
// https://github.com/indutny/elliptic/blob/e71b2d9359c5fe9437fbf46f1f05096de447de57/lib/elliptic/curves.js#L182
const N = new BN(
'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141'.replace(/ /g, ''),
'hex'
);
const N = 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141'.replace(/ /g, '');
const N_BI = BigInt(`0x${N}`);
const N_BN = new BN(N, 'hex');
export function secp256k1PrivateKeyTweakAdd (seckey: Uint8Array, tweak: Uint8Array): Uint8Array {
function addBi (seckey: Uint8Array, tweak: Uint8Array): Uint8Array {
let res = u8aToBigInt(tweak, BN_BE_OPTS);
assert(res < N_BI, 'Tweak parameter is out of range');
res += u8aToBigInt(seckey, BN_BE_OPTS);
if (res >= N_BI) {
res -= N_BI;
}
assert(res !== _0n, 'Invalid resulting private key');
return nToU8a(res, BN_BE_256_OPTS);
}
function addBn (seckey: Uint8Array, tweak: Uint8Array): Uint8Array {
const res = new BN(tweak);
assert(res.cmp(N_BN) < 0, 'Tweak parameter is out of range');
res.iadd(new BN(seckey));
if (res.cmp(N_BN) >= 0) {
res.isub(N_BN);
}
assert(!res.isZero(), 'Invalid resulting private key');
return bnToU8a(res, BN_BE_256_OPTS);
}
export function secp256k1PrivateKeyTweakAdd (seckey: Uint8Array, tweak: Uint8Array, onlyBn?: boolean): Uint8Array {
assert(isU8a(seckey) && seckey.length === 32, 'Expected seckey to be an Uint8Array with length 32');
assert(isU8a(tweak) && tweak.length === 32, 'Expected tweak to be an Uint8Array with length 32');
const bn = new BN(tweak);
assert(bn.cmp(N) < 0, 'Tweak parameter is out of range');
bn.iadd(new BN(seckey));
if (bn.cmp(N) >= 0) {
bn.isub(N);
}
assert(!bn.isZero(), 'Invalid resulting private key');
return bnToU8a(bn, BN_BE_256_OPTS);
return !hasBigInt || onlyBn
? addBn(seckey, tweak)
: addBi(seckey, tweak);
}
@@ -1,19 +1,73 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { secp256k1Verify } from '.';
import { hexToU8a } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { performanceWasm } from '../../test/performance';
import { secp256k1Hasher } from './hasher';
import { secp256k1PairFromSeed, secp256k1Verify } from '.';
const message = 'Pay KSMs to the Kusama account:88dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee';
describe('secp256k1Verify', (): void => {
it('validates known ETH against address', (): void => {
const message = 'Pay KSMs to the Kusama account:88dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee';
expect(
secp256k1Verify(
`\x19Ethereum Signed Message:\n${message.length.toString()}${message}`,
'0x55bd020bdbbdc02de34e915effc9b18a99002f4c29f64e22e8dcbb69e722ea6c28e1bb53b9484063fbbfd205e49dcc1f620929f520c9c4c3695150f05a28f52a01',
'0x002309df96687e44280bb72c3818358faeeb699c',
'keccak'
)
).toBe(true);
beforeEach(async (): Promise<void> => {
await waitReady();
});
describe.each([false, true])('onlyJs=%p', (onlyJs): void => {
it('validates known ETH against address', (): void => {
expect(
secp256k1Verify(
`\x19Ethereum Signed Message:\n${message.length.toString()}${message}`,
'0x55bd020bdbbdc02de34e915effc9b18a99002f4c29f64e22e8dcbb69e722ea6c28e1bb53b9484063fbbfd205e49dcc1f620929f520c9c4c3695150f05a28f52a01',
'0x002309df96687e44280bb72c3818358faeeb699c',
'keccak',
onlyJs
)
).toEqual(true);
});
describe.each([false, true])('validation against known, publicKey=%p', (isPublic): void => {
const pair = secp256k1PairFromSeed(hexToU8a('0x4380de832af797688026ce24f85204d508243f201650c1a134929e5458b7fbae'));
const msg = hexToU8a('0xa30b64ce1eedf409c8afb801d72c05234e64849ea538c15dd3c8cf4ffcf166c9');
const addr = isPublic
? pair.publicKey
: secp256k1Hasher('blake2', pair.publicKey, onlyJs);
it('signature from JS', (): void => {
expect(
secp256k1Verify(
msg,
'0xdf92f73d9f060cefacf187b5414491cb992998ace017fa48839b5cda3e264ba8c4efa521361678d9b8582744d77aa4b8d886d7380b7808a683174afad9c4700300',
addr,
'blake2',
onlyJs
)
).toEqual(true);
});
it('signature from wasm', (): void => {
expect(
secp256k1Verify(
msg,
'0xdf92f73d9f060cefacf187b5414491cb992998ace017fa48839b5cda3e264ba83b105adec9e9872647a7d8bb28855b45e22805aea3d097953cbb1391f671d13e01',
addr,
'blake2',
onlyJs
)
).toEqual(true);
});
});
});
performanceWasm('secp256k1Verify', 100, (_, onlyJs) =>
secp256k1Verify(
`\x19Ethereum Signed Message:\n${message.length.toString()}${message}`,
'0x55bd020bdbbdc02de34e915effc9b18a99002f4c29f64e22e8dcbb69e722ea6c28e1bb53b9484063fbbfd205e49dcc1f620929f520c9c4c3695150f05a28f52a01',
'0x002309df96687e44280bb72c3818358faeeb699c',
'keccak',
onlyJs
)
);
});
+15 -19
View File
@@ -6,36 +6,32 @@ import type { HashType } from './types';
import { assert, u8aEq, u8aToU8a } from '@polkadot/util';
import { secp256k1Expand } from './expand';
import { secp256k1Hasher } from './hasher';
import { secp256k1 } from './secp256k1';
import { secp256k1Recover } from './recover';
/**
* @name secp256k1Verify
* @description Verifies the signature of `message`, using the supplied pair
*/
export function secp256k1Verify (message: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, address: HexString | Uint8Array | string, hashType: HashType = 'blake2'): boolean {
const isEthereum = hashType === 'keccak';
export function secp256k1Verify (message: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, address: HexString | Uint8Array | string, hashType: HashType = 'blake2', onlyJs?: boolean): boolean {
const u8a = u8aToU8a(signature);
assert(u8a.length === 65, `Expected signature with 65 bytes, ${u8a.length} found instead`);
const publicKey = new Uint8Array(
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-argument
secp256k1
.recoverPubKey(
secp256k1Hasher(hashType, message),
{ r: u8a.slice(0, 32), s: u8a.slice(32, 64) },
u8a[64]
)
.encodeCompressed()
const publicKey = secp256k1Recover(
secp256k1Hasher(hashType, message),
u8a.subarray(0, 64),
u8a[64],
hashType,
onlyJs
);
const signingAddress = secp256k1Hasher(hashType, isEthereum ? secp256k1Expand(publicKey) : publicKey);
const inputAddress = u8aToU8a(address);
const signerAddr = secp256k1Hasher(hashType, publicKey, onlyJs);
const inputAddr = u8aToU8a(address);
// for Ethereum (keccak) the last 20 bytes is the address
return isEthereum
? u8aEq(signingAddress.slice(-20), inputAddress.slice(-20))
: u8aEq(signingAddress, inputAddress);
return u8aEq(publicKey, inputAddr) || (
hashType === 'keccak'
? u8aEq(signerAddr.slice(-20), inputAddr.slice(-20))
: u8aEq(signerAddr, inputAddr)
);
}
+2 -2
View File
@@ -10,8 +10,8 @@ type ExecFn = (input: Uint8Array, onlyJs: boolean) => unknown;
const GENERATED = arrayRange(256).map(() => [randomAsU8a()]);
export function performanceWasm (name: string, count: number, exec: ExecFn): void {
performanceCmp(name, ['WebAssembly', 'JavaScript'], count, GENERATED, exec);
export function performanceWasm (name: string, count: number, exec: ExecFn, inputs = GENERATED): void {
performanceCmp(name, ['WebAssembly', 'JavaScript'], count, inputs, exec);
}
export { performance, performanceCmp };