Wasm-compat for keccak512 & sha256 (#1216)

* Wasm-compa for keccak512 & sha256

* wasm/non-wasm tests

* linting

* Bump wasm

* formatting
This commit is contained in:
Jaco
2021-11-19 14:59:59 +02:00
committed by GitHub
parent 88580b98a6
commit 085862ce79
9 changed files with 144 additions and 37 deletions
@@ -42,4 +42,26 @@ describe('keccakAsU8a', (): void => {
});
});
});
it.skip.each([false, true])('performance: onlyJs=%p', (onlyJs): void => {
const label = `keccakAsU8a:onlyJs=${onlyJs.toString()}`;
const test = 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,
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
]);
console.time(label);
for (let i = 0; i < 128000; i++) {
keccakAsU8a(test, undefined, onlyJs);
}
console.timeEnd(label);
});
});
+7 -4
View File
@@ -6,7 +6,7 @@ import type { HexString } from '@polkadot/util/types';
import js from 'js-sha3';
import { u8aToU8a } from '@polkadot/util';
import { isReady, keccak256 } from '@polkadot/wasm-crypto';
import { isReady, keccak256, keccak512 } from '@polkadot/wasm-crypto';
/**
* @name keccakAsU8a
@@ -24,10 +24,13 @@ import { isReady, keccak256 } from '@polkadot/wasm-crypto';
*/
export function keccakAsU8a (value: HexString | Buffer | Uint8Array | string, bitLength: 256 | 512 = 256, onlyJs = false): Uint8Array {
const is256 = bitLength === 256;
const u8a = u8aToU8a(value);
return isReady() && is256 && !onlyJs
? keccak256(u8aToU8a(value))
return isReady() && !onlyJs
? is256
? keccak256(u8a)
: keccak512(u8a)
: new Uint8Array(
(is256 ? js.keccak256 : js.keccak512).update(u8aToU8a(value)).arrayBuffer()
(is256 ? js.keccak256 : js.keccak512).update(u8a).arrayBuffer()
);
}