Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
691a8e9b18 | ||
|
|
fc812590e5 | ||
|
|
05499abcd5 | ||
|
|
e375dd8a9d | ||
|
|
3269883e8f | ||
|
|
c99129ee06 | ||
|
|
2514e107bf | ||
|
|
3c34a0e1f2 | ||
|
|
f704e371c8 | ||
|
|
97e3443e74 | ||
|
|
a84e101666 | ||
|
|
a799918d58 | ||
|
|
429390fb62 | ||
|
|
05d0109b72 | ||
|
|
02b1429979 | ||
|
|
6e1853d01f | ||
|
|
aa9c406d01 | ||
|
|
f9ec44823d | ||
|
|
54218651f9 | ||
|
|
571c9eff6a | ||
|
|
5b7333b8dd | ||
|
|
938fa8b967 | ||
|
|
b99a69871e | ||
|
|
b1da8f575b | ||
|
|
a960aaf6ae | ||
|
|
f88c647ad0 | ||
|
|
7ff11925d9 | ||
|
|
cb5a588489 | ||
|
|
09019224e3 | ||
|
|
2d7031831a | ||
|
|
faf7ea2b17 | ||
|
|
af973de694 | ||
|
|
dfede866b2 | ||
|
|
0f0b243815 | ||
|
|
29f53fe906 | ||
|
|
225c250634 | ||
|
|
c871e9d735 | ||
|
|
b42ead28e5 | ||
|
|
db0581c051 | ||
|
|
e7ac095ace | ||
|
|
a7d9fc48e9 | ||
|
|
3db2990ce7 | ||
|
|
4b7cda243b | ||
|
|
c4ceeb8382 | ||
|
|
540971d388 | ||
|
|
b4d65a1c49 | ||
|
|
4fd4660853 | ||
|
|
4b46c179b2 | ||
|
|
3c6d297ecd | ||
|
|
4a6e620acc |
@@ -0,0 +1 @@
|
||||
9.6.2
|
||||
+2
-1
@@ -27,4 +27,5 @@
|
||||
8.1.2
|
||||
8.2.2
|
||||
8.3.2
|
||||
8.3.3
|
||||
8.3.3
|
||||
9.6.2
|
||||
@@ -3,6 +3,7 @@ _book/
|
||||
build/
|
||||
build-cjs/
|
||||
build-esm/
|
||||
build-deno/
|
||||
build-docs/
|
||||
coverage/
|
||||
docs/.vuepress/dist/
|
||||
|
||||
@@ -1,5 +1,21 @@
|
||||
# CHANGELOG
|
||||
|
||||
## 9.6.2 Jun 25, 2022
|
||||
|
||||
Changes:
|
||||
|
||||
- Fix `hexToU8a` where `0x` is not correctly converted
|
||||
|
||||
|
||||
## 9.6.1 Jun 23, 2022
|
||||
|
||||
Changes:
|
||||
|
||||
- Add `floatToU8a` and `u8aToFloat` (both 32 & 64-bit, le & be)
|
||||
- Adjust `isUndefined` check (local variable available)
|
||||
- Adjust use of `assert`, `isUndefined` & `isNull`
|
||||
|
||||
|
||||
## 9.5.1 Jun 18, 2022
|
||||
|
||||
Contributed:
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
1363 Jaco 9.5.1 (#1545)
|
||||
1388 Jaco Fix `hexToU8a` where `0x` is not correctly converted (#1567)
|
||||
9 Antoine Estienne Add eth uri keyring test (#1291)
|
||||
6 Amaury Martiny Add tests from Rust (#283)
|
||||
5 kwingram25 Add BN consts and timeToString (#610)
|
||||
|
||||
+4
-4
@@ -10,7 +10,7 @@
|
||||
"url": "https://github.com/polkadot-js/common.git"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"version": "9.5.1",
|
||||
"version": "9.6.2",
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
@@ -28,10 +28,10 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.18.5",
|
||||
"@polkadot/dev": "^0.67.4",
|
||||
"@types/jest": "^28.1.2"
|
||||
"@polkadot/dev": "^0.67.42",
|
||||
"@types/jest": "^28.1.3"
|
||||
},
|
||||
"resolutions": {
|
||||
"typescript": "^4.7.3"
|
||||
"typescript": "^4.7.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
},
|
||||
"sideEffects": false,
|
||||
"type": "module",
|
||||
"version": "9.5.1",
|
||||
"version": "9.6.2",
|
||||
"browser": "browser.js",
|
||||
"main": "node.js",
|
||||
"react-native": "react-native.js",
|
||||
@@ -25,7 +25,7 @@
|
||||
"@ledgerhq/hw-transport": "^6.27.1",
|
||||
"@ledgerhq/hw-transport-webhid": "^6.27.1",
|
||||
"@ledgerhq/hw-transport-webusb": "^6.27.1",
|
||||
"@polkadot/util": "9.5.1"
|
||||
"@polkadot/util": "9.6.2"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@ledgerhq/hw-transport-node-hid-singleton": "^6.27.1"
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
// Copyright 2017-2022 @polkadot/hw-ledger authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { TransportDef } from './types';
|
||||
|
||||
export { packageInfo } from './packageInfo';
|
||||
|
||||
export const transports: TransportDef[] = [];
|
||||
@@ -0,0 +1,4 @@
|
||||
// Copyright 2017-2022 @polkadot/hw-ledger authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export * from './empty';
|
||||
@@ -3,4 +3,4 @@
|
||||
|
||||
// Do not edit, auto-generated by @polkadot/dev
|
||||
|
||||
export const packageInfo = { name: '@polkadot/hw-ledger-transports', path: 'auto', type: 'auto', version: '9.5.1' };
|
||||
export const packageInfo = { name: '@polkadot/hw-ledger-transports', path: 'auto', type: 'auto', version: '9.6.2' };
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
// Copyright 2017-2022 @polkadot/hw-ledger authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { TransportDef } from './types';
|
||||
|
||||
export { packageInfo } from './packageInfo';
|
||||
|
||||
export const transports: TransportDef[] = [];
|
||||
export * from './empty';
|
||||
|
||||
@@ -19,13 +19,13 @@
|
||||
"./detectPackage.cjs"
|
||||
],
|
||||
"type": "module",
|
||||
"version": "9.5.1",
|
||||
"version": "9.6.2",
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.18.3",
|
||||
"@ledgerhq/hw-transport": "^6.27.1",
|
||||
"@polkadot/hw-ledger-transports": "9.5.1",
|
||||
"@polkadot/util": "9.5.1",
|
||||
"@polkadot/hw-ledger-transports": "9.6.2",
|
||||
"@polkadot/util": "9.6.2",
|
||||
"@zondax/ledger-substrate": "^0.31.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { ResponseBase, SubstrateApp } from '@zondax/ledger-substrate';
|
||||
import type { AccountOptions, LedgerAddress, LedgerSignature, LedgerTypes, LedgerVersion } from './types';
|
||||
|
||||
import { transports } from '@polkadot/hw-ledger-transports';
|
||||
import { assert, u8aToBuffer } from '@polkadot/util';
|
||||
import { u8aToBuffer } from '@polkadot/util';
|
||||
|
||||
import { LEDGER_DEFAULT_ACCOUNT, LEDGER_DEFAULT_CHANGE, LEDGER_DEFAULT_INDEX, LEDGER_SUCCESS_CODE } from './constants';
|
||||
import { ledgerApps } from './defaults';
|
||||
@@ -26,8 +26,11 @@ export class Ledger {
|
||||
|
||||
constructor (transport: LedgerTypes, chain: Chain) {
|
||||
// u2f is deprecated
|
||||
assert(['hid', 'webusb'].includes(transport), () => `Unsupported transport ${transport}`);
|
||||
assert(Object.keys(ledgerApps).includes(chain), () => `Unsupported chain ${chain}`);
|
||||
if (!['hid', 'webusb'].includes(transport)) {
|
||||
throw new Error(`Unsupported transport ${transport}`);
|
||||
} else if (!Object.keys(ledgerApps).includes(chain)) {
|
||||
throw new Error(`Unsupported chain ${chain}`);
|
||||
}
|
||||
|
||||
this.#chain = chain;
|
||||
this.#transport = transport;
|
||||
@@ -71,7 +74,9 @@ export class Ledger {
|
||||
if (!this.#app) {
|
||||
const def = transports.find(({ type }) => type === this.#transport);
|
||||
|
||||
assert(def, () => `Unable to find a transport for ${this.#transport}`);
|
||||
if (!def) {
|
||||
throw new Error(`Unable to find a transport for ${this.#transport}`);
|
||||
}
|
||||
|
||||
const transport = await def.create();
|
||||
|
||||
@@ -96,7 +101,9 @@ export class Ledger {
|
||||
#wrapError = async <T extends ResponseBase> (promise: Promise<T>): Promise<T> => {
|
||||
const result = await promise;
|
||||
|
||||
assert(result.return_code === LEDGER_SUCCESS_CODE, () => result.error_message);
|
||||
if (result.return_code !== LEDGER_SUCCESS_CODE) {
|
||||
throw new Error(result.error_message);
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
// Copyright 2017-2022 @polkadot/hw-ledger authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export * from './index';
|
||||
@@ -3,4 +3,4 @@
|
||||
|
||||
// Do not edit, auto-generated by @polkadot/dev
|
||||
|
||||
export const packageInfo = { name: '@polkadot/hw-ledger', path: 'auto', type: 'auto', version: '9.5.1' };
|
||||
export const packageInfo = { name: '@polkadot/hw-ledger', path: 'auto', type: 'auto', version: '9.6.2' };
|
||||
|
||||
@@ -20,15 +20,15 @@
|
||||
"./detectPackage.cjs"
|
||||
],
|
||||
"type": "module",
|
||||
"version": "9.5.1",
|
||||
"version": "9.6.2",
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.18.3",
|
||||
"@polkadot/util": "9.5.1",
|
||||
"@polkadot/util-crypto": "9.5.1"
|
||||
"@polkadot/util": "9.6.2",
|
||||
"@polkadot/util-crypto": "9.6.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@polkadot/util": "9.5.1",
|
||||
"@polkadot/util-crypto": "9.5.1"
|
||||
"@polkadot/util": "9.6.2",
|
||||
"@polkadot/util-crypto": "9.6.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import type { EncryptedJsonEncoding, Keypair, KeypairType } from '@polkadot/util-crypto/types';
|
||||
import type { KeyringInstance, KeyringOptions, KeyringPair, KeyringPair$Json, KeyringPair$Meta } from './types';
|
||||
|
||||
import { assert, hexToU8a, isHex, isUndefined, stringToU8a } from '@polkadot/util';
|
||||
import { hexToU8a, isHex, stringToU8a } from '@polkadot/util';
|
||||
import { base64Decode, decodeAddress, ed25519PairFromSeed as ed25519FromSeed, encodeAddress, ethereumEncode, hdEthereum, keyExtractSuri, keyFromPath, mnemonicToLegacySeed, mnemonicToMiniSecret, secp256k1PairFromSeed as secp256k1FromSeed, sr25519PairFromSeed as sr25519FromSeed } from '@polkadot/util-crypto';
|
||||
|
||||
import { DEV_PHRASE } from './defaults';
|
||||
@@ -50,7 +50,9 @@ export class Keyring implements KeyringInstance {
|
||||
constructor (options: KeyringOptions = {}) {
|
||||
options.type = options.type || 'ed25519';
|
||||
|
||||
assert(['ecdsa', 'ethereum', 'ed25519', 'sr25519'].includes(options.type || 'undefined'), () => `Expected a keyring type of either 'ed25519', 'sr25519', 'ethereum' or 'ecdsa', found '${options.type || 'unknown'}`);
|
||||
if (!['ecdsa', 'ethereum', 'ed25519', 'sr25519'].includes(options.type || 'undefined')) {
|
||||
throw new Error(`Expected a keyring type of either 'ed25519', 'sr25519', 'ethereum' or 'ecdsa', found '${options.type || 'unknown'}`);
|
||||
}
|
||||
|
||||
this.#pairs = new Pairs();
|
||||
this.#ss58 = options.ss58Format;
|
||||
@@ -162,7 +164,9 @@ export class Keyring implements KeyringInstance {
|
||||
* @description Creates a pair from a JSON keyfile
|
||||
*/
|
||||
public createFromJson ({ address, encoded, encoding: { content, type, version }, meta }: KeyringPair$Json, ignoreChecksum?: boolean): KeyringPair {
|
||||
assert(version !== '3' || content[0] === 'pkcs8', () => `Unable to decode non-pkcs8 type, [${content.join(',')}] found}`);
|
||||
if (version === '3' && content[0] !== 'pkcs8') {
|
||||
throw new Error(`Unable to decode non-pkcs8 type, [${content.join(',')}] found}`);
|
||||
}
|
||||
|
||||
const cryptoType = version === '0' || !Array.isArray(content)
|
||||
? this.type
|
||||
@@ -171,7 +175,9 @@ export class Keyring implements KeyringInstance {
|
||||
? [type]
|
||||
: type;
|
||||
|
||||
assert(['ed25519', 'sr25519', 'ecdsa', 'ethereum'].includes(cryptoType), () => `Unknown crypto type ${cryptoType}`);
|
||||
if (!['ed25519', 'sr25519', 'ecdsa', 'ethereum'].includes(cryptoType)) {
|
||||
throw new Error(`Unknown crypto type ${cryptoType}`);
|
||||
}
|
||||
|
||||
// Here the address and publicKey are 32 bytes and isomorphic. This is why the address field needs to be the public key for ethereum type pairs
|
||||
const publicKey = isHex(address)
|
||||
@@ -216,7 +222,9 @@ export class Keyring implements KeyringInstance {
|
||||
? mnemonicToLegacySeed(phrase, '', false, 64)
|
||||
: mnemonicToMiniSecret(phrase, password);
|
||||
} else {
|
||||
assert(phrase.length <= 32, 'specified phrase is not a valid mnemonic and is invalid as a raw seed at > 32 bytes');
|
||||
if (phrase.length > 32) {
|
||||
throw new Error('specified phrase is not a valid mnemonic and is invalid as a raw seed at > 32 bytes');
|
||||
}
|
||||
|
||||
seed = stringToU8a(phrase.padEnd(32));
|
||||
}
|
||||
@@ -238,7 +246,7 @@ export class Keyring implements KeyringInstance {
|
||||
public encodeAddress = (address: Uint8Array | string, ss58Format?: number): string => {
|
||||
return this.type === 'ethereum'
|
||||
? ethereumEncode(address)
|
||||
: encodeAddress(address, isUndefined(ss58Format) ? this.#ss58 : ss58Format);
|
||||
: encodeAddress(address, ss58Format === undefined ? this.#ss58 : ss58Format);
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
// Copyright 2017-2022 @polkadot/keyring authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export * from './index';
|
||||
@@ -3,4 +3,4 @@
|
||||
|
||||
// Do not edit, auto-generated by @polkadot/dev
|
||||
|
||||
export const packageInfo = { name: '@polkadot/keyring', path: 'auto', type: 'auto', version: '9.5.1' };
|
||||
export const packageInfo = { name: '@polkadot/keyring', path: 'auto', type: 'auto', version: '9.6.2' };
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import type { EncryptedJsonEncoding } from '@polkadot/util-crypto/types';
|
||||
import type { PairInfo } from './types';
|
||||
|
||||
import { assert, isUndefined, u8aEq } from '@polkadot/util';
|
||||
import { assert, u8aEq } from '@polkadot/util';
|
||||
import { jsonDecryptData } from '@polkadot/util-crypto';
|
||||
|
||||
import { PKCS8_DIVIDER, PKCS8_HEADER, PUB_LENGTH, SEC_LENGTH, SEED_LENGTH } from './defaults';
|
||||
@@ -16,7 +16,7 @@ type DecodeResult = PairInfo & {
|
||||
};
|
||||
|
||||
export function decodePair (passphrase?: string, encrypted?: Uint8Array | null, _encType?: EncryptedJsonEncoding | EncryptedJsonEncoding[]): DecodeResult {
|
||||
const encType = Array.isArray(_encType) || isUndefined(_encType)
|
||||
const encType = Array.isArray(_encType) || _encType === undefined
|
||||
? _encType
|
||||
: [_encType];
|
||||
const decrypted = jsonDecryptData(encrypted, passphrase, encType);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { KeyringPair, KeyringPairs } from './types';
|
||||
|
||||
import { assert, isHex, isU8a, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
import { isHex, isU8a, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
import { decodeAddress } from '@polkadot/util-crypto';
|
||||
|
||||
type KeyringPairMap = Record<string, KeyringPair>;
|
||||
@@ -25,11 +25,13 @@ export class Pairs implements KeyringPairs {
|
||||
public get (address: HexString | string | Uint8Array): KeyringPair {
|
||||
const pair = this.#map[decodeAddress(address).toString()];
|
||||
|
||||
assert(pair, () => `Unable to retrieve keypair '${
|
||||
isU8a(address) || isHex(address)
|
||||
? u8aToHex(u8aToU8a(address))
|
||||
: address
|
||||
}'`);
|
||||
if (!pair) {
|
||||
throw new Error(`Unable to retrieve keypair '${
|
||||
isU8a(address) || isHex(address)
|
||||
? u8aToHex(u8aToU8a(address))
|
||||
: address
|
||||
}'`);
|
||||
}
|
||||
|
||||
return pair;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import type { KeyringInstance, KeyringOptions } from './types';
|
||||
|
||||
import { assert, hexToU8a } from '@polkadot/util';
|
||||
import { hexToU8a } from '@polkadot/util';
|
||||
import { KeypairType } from '@polkadot/util-crypto/types';
|
||||
|
||||
import { Keyring } from './keyring';
|
||||
@@ -112,7 +112,9 @@ export const PAIRSETHEREUM: PairDef[] = [
|
||||
];
|
||||
|
||||
function createMeta (name?: string, seed?: string) {
|
||||
assert(name || seed, 'Testing pair should have either a name or a seed');
|
||||
if (!name && !seed) {
|
||||
throw new Error('Testing pair should have either a name or a seed');
|
||||
}
|
||||
|
||||
return {
|
||||
isTesting: true,
|
||||
|
||||
@@ -17,15 +17,15 @@
|
||||
},
|
||||
"sideEffects": false,
|
||||
"type": "module",
|
||||
"version": "9.5.1",
|
||||
"version": "9.6.2",
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.18.3",
|
||||
"@polkadot/util": "9.5.1",
|
||||
"@polkadot/util": "9.6.2",
|
||||
"@substrate/ss58-registry": "^1.22.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/hw-ledger": "9.5.1",
|
||||
"@polkadot/x-fetch": "9.5.1"
|
||||
"@polkadot/hw-ledger": "9.6.2",
|
||||
"@polkadot/x-fetch": "9.6.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
// Copyright 2017-2022 @polkadot/networks authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export * from './index';
|
||||
@@ -3,4 +3,4 @@
|
||||
|
||||
// Do not edit, auto-generated by @polkadot/dev
|
||||
|
||||
export const packageInfo = { name: '@polkadot/networks', path: 'auto', type: 'auto', version: '9.5.1' };
|
||||
export const packageInfo = { name: '@polkadot/networks', path: 'auto', type: 'auto', version: '9.6.2' };
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
"./detectPackage.cjs"
|
||||
],
|
||||
"type": "module",
|
||||
"version": "9.5.1",
|
||||
"version": "9.6.2",
|
||||
"browser": {
|
||||
"crypto": false,
|
||||
"stream": false
|
||||
@@ -30,13 +30,13 @@
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.18.3",
|
||||
"@noble/hashes": "1.1.1",
|
||||
"@noble/hashes": "1.1.2",
|
||||
"@noble/secp256k1": "1.6.0",
|
||||
"@polkadot/networks": "9.5.1",
|
||||
"@polkadot/util": "9.5.1",
|
||||
"@polkadot/wasm-crypto": "^6.1.1",
|
||||
"@polkadot/x-bigint": "9.5.1",
|
||||
"@polkadot/x-randomvalues": "9.5.1",
|
||||
"@polkadot/networks": "9.6.2",
|
||||
"@polkadot/util": "9.6.2",
|
||||
"@polkadot/wasm-crypto": "^6.1.5",
|
||||
"@polkadot/x-bigint": "9.6.2",
|
||||
"@polkadot/x-randomvalues": "9.6.2",
|
||||
"@scure/base": "1.1.1",
|
||||
"ed2curve": "^0.3.0",
|
||||
"tweetnacl": "^1.0.3"
|
||||
@@ -45,6 +45,6 @@
|
||||
"@types/ed2curve": "^0.2.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@polkadot/util": "9.5.1"
|
||||
"@polkadot/util": "9.6.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { assert, isNull } from '@polkadot/util';
|
||||
|
||||
import { DeriveJunction } from './DeriveJunction';
|
||||
import { keyExtractPath } from './extractPath';
|
||||
|
||||
@@ -22,7 +20,9 @@ export function keyExtractSuri (suri: string): ExtractResult {
|
||||
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
|
||||
const matches = suri.match(RE_CAPTURE);
|
||||
|
||||
assert(!isNull(matches), 'Unable to match provided value to a secret URI');
|
||||
if (matches === null) {
|
||||
throw new Error('Unable to match provided value to a secret URI');
|
||||
}
|
||||
|
||||
const [, phrase, , derivePath, , , password] = matches as string[];
|
||||
const { path } = keyExtractPath(derivePath);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { assert, hasBigInt } from '@polkadot/util';
|
||||
import { hasBigInt } from '@polkadot/util';
|
||||
import { bip39ToSeed, isReady } from '@polkadot/wasm-crypto';
|
||||
|
||||
import { mnemonicToSeedSync } from './bip39';
|
||||
@@ -25,8 +25,11 @@ import { mnemonicValidate } from './validate';
|
||||
* ```
|
||||
*/
|
||||
export function mnemonicToLegacySeed (mnemonic: string, password = '', onlyJs?: boolean, byteLength: 32 | 64 = 32): Uint8Array {
|
||||
assert(mnemonicValidate(mnemonic), 'Invalid bip39 mnemonic specified');
|
||||
assert([32, 64].includes(byteLength), () => `Invalid seed length ${byteLength}, expected 32 or 64`);
|
||||
if (!mnemonicValidate(mnemonic)) {
|
||||
throw new Error('Invalid bip39 mnemonic specified');
|
||||
} else if (![32, 64].includes(byteLength)) {
|
||||
throw new Error(`Invalid seed length ${byteLength}, expected 32 or 64`);
|
||||
}
|
||||
|
||||
return byteLength === 32
|
||||
? !hasBigInt || (!onlyJs && isReady())
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { assert, stringToU8a } from '@polkadot/util';
|
||||
import { stringToU8a } from '@polkadot/util';
|
||||
import { bip39ToMiniSecret, isReady } from '@polkadot/wasm-crypto';
|
||||
|
||||
import { pbkdf2Encode } from '../pbkdf2';
|
||||
@@ -9,7 +9,9 @@ import { mnemonicToEntropy } from './toEntropy';
|
||||
import { mnemonicValidate } from './validate';
|
||||
|
||||
export function mnemonicToMiniSecret (mnemonic: string, password = '', onlyJs?: boolean): Uint8Array {
|
||||
assert(mnemonicValidate(mnemonic), 'Invalid bip39 mnemonic specified');
|
||||
if (!mnemonicValidate(mnemonic)) {
|
||||
throw new Error('Invalid bip39 mnemonic specified');
|
||||
}
|
||||
|
||||
if (!onlyJs && isReady()) {
|
||||
return bip39ToMiniSecret(mnemonic, password);
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export * from './index';
|
||||
@@ -3,4 +3,4 @@
|
||||
|
||||
// Do not edit, auto-generated by @polkadot/dev
|
||||
|
||||
export const packageInfo = { name: '@polkadot/util-crypto', path: 'auto', type: 'auto', version: '9.5.1' };
|
||||
export const packageInfo = { name: '@polkadot/util-crypto', path: 'auto', type: 'auto', version: '9.6.2' };
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import type { Params } from './types';
|
||||
|
||||
import { assert, u8aToBn } from '@polkadot/util';
|
||||
import { u8aToBn } from '@polkadot/util';
|
||||
|
||||
import { BN_LE_OPTS } from '../bn';
|
||||
import { DEFAULT_PARAMS } from './defaults';
|
||||
@@ -23,7 +23,9 @@ export function scryptFromU8a (data: Uint8Array): Result {
|
||||
// and updates for greater security. However we need some protection against carefully-crafted params that can
|
||||
// eat up CPU since these are user inputs. So we need to get very clever here, but atm we only allow the defaults
|
||||
// and if no match, bail out
|
||||
assert(N === DEFAULT_PARAMS.N && p === DEFAULT_PARAMS.p && r === DEFAULT_PARAMS.r, 'Invalid injected scrypt params found');
|
||||
if (N !== DEFAULT_PARAMS.N || p !== DEFAULT_PARAMS.p || r !== DEFAULT_PARAMS.r) {
|
||||
throw new Error('Invalid injected scrypt params found');
|
||||
}
|
||||
|
||||
return { params: { N, p, r }, salt };
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import { Point } from '@noble/secp256k1';
|
||||
|
||||
import { assert, hasBigInt } from '@polkadot/util';
|
||||
import { hasBigInt } from '@polkadot/util';
|
||||
import { isReady, secp256k1Compress as wasm } from '@polkadot/wasm-crypto';
|
||||
|
||||
export function secp256k1Compress (publicKey: Uint8Array, onlyJs?: boolean): Uint8Array {
|
||||
@@ -11,7 +11,9 @@ export function secp256k1Compress (publicKey: Uint8Array, onlyJs?: boolean): Uin
|
||||
return publicKey;
|
||||
}
|
||||
|
||||
assert(publicKey.length === 65, 'Invalid publicKey provided');
|
||||
if (publicKey.length !== 65) {
|
||||
throw new Error('Invalid publicKey provided');
|
||||
}
|
||||
|
||||
return !hasBigInt || (!onlyJs && isReady())
|
||||
? wasm(publicKey)
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { assert, compactAddLength, isU8a, stringToU8a, u8aConcat } from '@polkadot/util';
|
||||
import { compactAddLength, isU8a, stringToU8a, u8aConcat } from '@polkadot/util';
|
||||
|
||||
import { blake2AsU8a } from '../blake2/asU8a';
|
||||
|
||||
const HDKD = compactAddLength(stringToU8a('Secp256k1HDKD'));
|
||||
|
||||
export function secp256k1DeriveHard (seed: Uint8Array, chainCode: Uint8Array): Uint8Array {
|
||||
assert(isU8a(chainCode) && chainCode.length === 32, 'Invalid chainCode passed to derive');
|
||||
if (!isU8a(chainCode) || chainCode.length !== 32) {
|
||||
throw new Error('Invalid chainCode passed to derive');
|
||||
}
|
||||
|
||||
// NOTE This is specific to the Substrate HDD derivation, so always use the blake2 hasher
|
||||
return blake2AsU8a(u8aConcat(HDKD, seed, chainCode), 256);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import { Point } from '@noble/secp256k1';
|
||||
|
||||
import { assert, bnToU8a, hasBigInt, u8aConcat } from '@polkadot/util';
|
||||
import { bnToU8a, hasBigInt, u8aConcat } from '@polkadot/util';
|
||||
import { isReady, secp256k1Expand as wasm } from '@polkadot/wasm-crypto';
|
||||
|
||||
import { BN_BE_256_OPTS } from '../bn';
|
||||
@@ -13,7 +13,9 @@ export function secp256k1Expand (publicKey: Uint8Array, onlyJs?: boolean): Uint8
|
||||
return publicKey.subarray(1);
|
||||
}
|
||||
|
||||
assert(publicKey.length === 33, 'Invalid publicKey provided');
|
||||
if (publicKey.length !== 33) {
|
||||
throw new Error('Invalid publicKey provided');
|
||||
}
|
||||
|
||||
if (!hasBigInt || (!onlyJs && isReady())) {
|
||||
return wasm(publicKey).subarray(1);
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { Keypair } from '../../types';
|
||||
|
||||
import { getPublicKey } from '@noble/secp256k1';
|
||||
|
||||
import { assert, hasBigInt, u8aEmpty } from '@polkadot/util';
|
||||
import { hasBigInt, u8aEmpty } from '@polkadot/util';
|
||||
import { isReady, secp256k1FromSeed } from '@polkadot/wasm-crypto';
|
||||
|
||||
/**
|
||||
@@ -13,7 +13,9 @@ import { isReady, secp256k1FromSeed } from '@polkadot/wasm-crypto';
|
||||
* @description Returns a object containing a `publicKey` & `secretKey` generated from the supplied seed.
|
||||
*/
|
||||
export function secp256k1PairFromSeed (seed: Uint8Array, onlyJs?: boolean): Keypair {
|
||||
assert(seed.length === 32, 'Expected valid 32-byte private key as a seed');
|
||||
if (seed.length !== 32) {
|
||||
throw new Error('Expected valid 32-byte private key as a seed');
|
||||
}
|
||||
|
||||
if (!hasBigInt || (!onlyJs && isReady())) {
|
||||
const full = secp256k1FromSeed(seed);
|
||||
@@ -23,7 +25,9 @@ export function secp256k1PairFromSeed (seed: Uint8Array, onlyJs?: boolean): Keyp
|
||||
// it seems that the lazy static section yields invalid results on the _first_ run.
|
||||
// If this happens, fail outright, we cannot allow invalid return values
|
||||
// https://github.com/polkadot-js/wasm/issues/307
|
||||
assert(!u8aEmpty(publicKey), 'Invalid publicKey generated from WASM interface');
|
||||
if (u8aEmpty(publicKey)) {
|
||||
throw new Error('Invalid publicKey generated from WASM interface');
|
||||
}
|
||||
|
||||
return {
|
||||
publicKey,
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { HashType } from './types';
|
||||
|
||||
import { recoverPublicKey, Signature } from '@noble/secp256k1';
|
||||
|
||||
import { assert, hasBigInt, u8aToU8a } from '@polkadot/util';
|
||||
import { hasBigInt, u8aToU8a } from '@polkadot/util';
|
||||
import { isReady, secp256k1Recover as wasm } from '@polkadot/wasm-crypto';
|
||||
|
||||
import { secp256k1Compress } from './compress';
|
||||
@@ -23,7 +23,9 @@ export function secp256k1Recover (msgHash: HexString | Uint8Array | string, sign
|
||||
? wasm(msg, sig, recovery)
|
||||
: recoverPublicKey(msg, Signature.fromCompact(sig).toRawBytes(), recovery);
|
||||
|
||||
assert(publicKey, 'Unable to recover publicKey from signature');
|
||||
if (!publicKey) {
|
||||
throw new Error('Unable to recover publicKey from signature');
|
||||
}
|
||||
|
||||
return hashType === 'keccak'
|
||||
? secp256k1Expand(publicKey, onlyJs)
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { HashType } from './types';
|
||||
|
||||
import { Signature, signSync } from '@noble/secp256k1';
|
||||
|
||||
import { assert, bnToU8a, hasBigInt, u8aConcat } from '@polkadot/util';
|
||||
import { bnToU8a, hasBigInt, u8aConcat } from '@polkadot/util';
|
||||
import { isReady, secp256k1Sign as wasm } from '@polkadot/wasm-crypto';
|
||||
|
||||
import { BN_BE_256_OPTS } from '../bn';
|
||||
@@ -17,7 +17,9 @@ import { hasher } from './hasher';
|
||||
* @description Returns message signature of `message`, using the supplied pair
|
||||
*/
|
||||
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');
|
||||
if (secretKey?.length !== 32) {
|
||||
throw new Error('Expected valid secp256k1 secretKey, 32-bytes');
|
||||
}
|
||||
|
||||
const data = hasher(hashType, message, onlyJs);
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { _0n, assert, BN, bnToU8a, hasBigInt, isU8a, nToU8a, u8aToBigInt } from '@polkadot/util';
|
||||
import { _0n, BN, bnToU8a, hasBigInt, isU8a, nToU8a, u8aToBigInt } from '@polkadot/util';
|
||||
import { BigInt } from '@polkadot/x-bigint';
|
||||
|
||||
import { BN_BE_256_OPTS, BN_BE_OPTS } from '../bn';
|
||||
@@ -15,7 +15,9 @@ const N_BN = new BN(N, 'hex');
|
||||
function addBi (seckey: Uint8Array, tweak: Uint8Array): Uint8Array {
|
||||
let res = u8aToBigInt(tweak, BN_BE_OPTS);
|
||||
|
||||
assert(res < N_BI, 'Tweak parameter is out of range');
|
||||
if (res >= N_BI) {
|
||||
throw new Error('Tweak parameter is out of range');
|
||||
}
|
||||
|
||||
res += u8aToBigInt(seckey, BN_BE_OPTS);
|
||||
|
||||
@@ -23,7 +25,9 @@ function addBi (seckey: Uint8Array, tweak: Uint8Array): Uint8Array {
|
||||
res -= N_BI;
|
||||
}
|
||||
|
||||
assert(res !== _0n, 'Invalid resulting private key');
|
||||
if (res === _0n) {
|
||||
throw new Error('Invalid resulting private key');
|
||||
}
|
||||
|
||||
return nToU8a(res, BN_BE_256_OPTS);
|
||||
}
|
||||
@@ -31,7 +35,9 @@ function addBi (seckey: Uint8Array, tweak: Uint8Array): Uint8Array {
|
||||
function addBn (seckey: Uint8Array, tweak: Uint8Array): Uint8Array {
|
||||
const res = new BN(tweak);
|
||||
|
||||
assert(res.cmp(N_BN) < 0, 'Tweak parameter is out of range');
|
||||
if (res.cmp(N_BN) >= 0) {
|
||||
throw new Error('Tweak parameter is out of range');
|
||||
}
|
||||
|
||||
res.iadd(new BN(seckey));
|
||||
|
||||
@@ -39,14 +45,19 @@ function addBn (seckey: Uint8Array, tweak: Uint8Array): Uint8Array {
|
||||
res.isub(N_BN);
|
||||
}
|
||||
|
||||
assert(!res.isZero(), 'Invalid resulting private key');
|
||||
if (res.isZero()) {
|
||||
throw new Error('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');
|
||||
if (!isU8a(seckey) || seckey.length !== 32) {
|
||||
throw new Error('Expected seckey to be an Uint8Array with length 32');
|
||||
} else if (!isU8a(tweak) || tweak.length !== 32) {
|
||||
throw new Error('Expected tweak to be an Uint8Array with length 32');
|
||||
}
|
||||
|
||||
return !hasBigInt || onlyBn
|
||||
? addBn(seckey, tweak)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { HashType } from './types';
|
||||
|
||||
import { assert, u8aEq, u8aToU8a } from '@polkadot/util';
|
||||
import { u8aEq, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { hasher } from './hasher';
|
||||
import { secp256k1Recover } from './recover';
|
||||
@@ -16,7 +16,9 @@ import { secp256k1Recover } from './recover';
|
||||
export function secp256k1Verify (msgHash: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, address: HexString | Uint8Array | string, hashType: HashType = 'blake2', onlyJs?: boolean): boolean {
|
||||
const sig = u8aToU8a(signature);
|
||||
|
||||
assert(sig.length === 65, `Expected signature with 65 bytes, ${sig.length} found instead`);
|
||||
if (sig.length !== 65) {
|
||||
throw new Error(`Expected signature with 65 bytes, ${sig.length} found instead`);
|
||||
}
|
||||
|
||||
const publicKey = secp256k1Recover(hasher(hashType, msgHash), sig, sig[64], hashType, onlyJs);
|
||||
const signerAddr = hasher(hashType, publicKey, onlyJs);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { KeypairType, VerifyResult } from '../types';
|
||||
|
||||
import { assert, u8aIsWrapped, u8aToU8a, u8aUnwrapBytes, u8aWrapBytes } from '@polkadot/util';
|
||||
import { u8aIsWrapped, u8aToU8a, u8aUnwrapBytes, u8aWrapBytes } from '@polkadot/util';
|
||||
|
||||
import { decodeAddress } from '../address/decode';
|
||||
import { ed25519Verify } from '../ed25519/verify';
|
||||
@@ -57,7 +57,9 @@ function verifyDetect (result: VerifyResult, { message, publicKey, signature }:
|
||||
}
|
||||
|
||||
function verifyMultisig (result: VerifyResult, { message, publicKey, signature }: VerifyInput): VerifyResult {
|
||||
assert([0, 1, 2].includes(signature[0]), () => `Unknown crypto type, expected signature prefix [0..2], found ${signature[0]}`);
|
||||
if (![0, 1, 2].includes(signature[0])) {
|
||||
throw new Error(`Unknown crypto type, expected signature prefix [0..2], found ${signature[0]}`);
|
||||
}
|
||||
|
||||
const type = CRYPTO_TYPES[signature[0]] || 'none';
|
||||
|
||||
@@ -88,7 +90,9 @@ function getVerifyFn (signature: Uint8Array): VerifyFn {
|
||||
export function signatureVerify (message: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, addressOrPublicKey: HexString | Uint8Array | string): VerifyResult {
|
||||
const signatureU8a = u8aToU8a(signature);
|
||||
|
||||
assert([64, 65, 66].includes(signatureU8a.length), () => `Invalid signature length, expected [64..66] bytes, found ${signatureU8a.length}`);
|
||||
if (![64, 65, 66].includes(signatureU8a.length)) {
|
||||
throw new Error(`Invalid signature length, expected [64..66] bytes, found ${signatureU8a.length}`);
|
||||
}
|
||||
|
||||
const publicKey = decodeAddress(addressOrPublicKey);
|
||||
const input = { message: u8aToU8a(message), publicKey, signature: signatureU8a };
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
|
||||
import { assert, u8aToU8a } from '@polkadot/util';
|
||||
import { u8aToU8a } from '@polkadot/util';
|
||||
import { sr25519Agree } from '@polkadot/wasm-crypto';
|
||||
|
||||
/**
|
||||
@@ -14,8 +14,11 @@ export function sr25519Agreement (secretKey: HexString | Uint8Array | string, pu
|
||||
const secretKeyU8a = u8aToU8a(secretKey);
|
||||
const publicKeyU8a = u8aToU8a(publicKey);
|
||||
|
||||
assert(publicKeyU8a.length === 32, () => `Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
|
||||
assert(secretKeyU8a.length === 64, () => `Invalid secretKey, received ${secretKeyU8a.length} bytes, expected 64`);
|
||||
if (publicKeyU8a.length !== 32) {
|
||||
throw new Error(`Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
|
||||
} else if (secretKeyU8a.length !== 64) {
|
||||
throw new Error(`Invalid secretKey, received ${secretKeyU8a.length} bytes, expected 64`);
|
||||
}
|
||||
|
||||
return sr25519Agree(publicKeyU8a, secretKeyU8a);
|
||||
}
|
||||
|
||||
@@ -3,14 +3,16 @@
|
||||
|
||||
import type { Keypair } from '../types';
|
||||
|
||||
import { assert, isU8a } from '@polkadot/util';
|
||||
import { isU8a } from '@polkadot/util';
|
||||
|
||||
import { sr25519PairFromU8a } from './pair/fromU8a';
|
||||
import { sr25519KeypairToU8a } from './pair/toU8a';
|
||||
|
||||
export function createDeriveFn (derive: (pair: Uint8Array, cc: Uint8Array) => Uint8Array): (keypair: Keypair, chainCode: Uint8Array) => Keypair {
|
||||
return (keypair: Keypair, chainCode: Uint8Array): Keypair => {
|
||||
assert(isU8a(chainCode) && chainCode.length === 32, 'Invalid chainCode passed to derive');
|
||||
if (!isU8a(chainCode) || chainCode.length !== 32) {
|
||||
throw new Error('Invalid chainCode passed to derive');
|
||||
}
|
||||
|
||||
return sr25519PairFromU8a(
|
||||
derive(sr25519KeypairToU8a(keypair), chainCode)
|
||||
|
||||
@@ -3,14 +3,17 @@
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
|
||||
import { assert, isU8a, u8aToU8a } from '@polkadot/util';
|
||||
import { isU8a, u8aToU8a } from '@polkadot/util';
|
||||
import { sr25519DerivePublicSoft } from '@polkadot/wasm-crypto';
|
||||
|
||||
export function sr25519DerivePublic (publicKey: HexString | Uint8Array | string, chainCode: Uint8Array): Uint8Array {
|
||||
const publicKeyU8a = u8aToU8a(publicKey);
|
||||
|
||||
assert(isU8a(chainCode) && chainCode.length === 32, 'Invalid chainCode passed to derive');
|
||||
assert(publicKeyU8a.length === 32, () => `Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
|
||||
if (!isU8a(chainCode) || chainCode.length !== 32) {
|
||||
throw new Error('Invalid chainCode passed to derive');
|
||||
} else if (publicKeyU8a.length !== 32) {
|
||||
throw new Error(`Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
|
||||
}
|
||||
|
||||
return sr25519DerivePublicSoft(publicKeyU8a, chainCode);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Keypair } from '../../types';
|
||||
|
||||
import { assert, u8aToU8a } from '@polkadot/util';
|
||||
import { u8aToU8a } from '@polkadot/util';
|
||||
import { sr25519KeypairFromSeed } from '@polkadot/wasm-crypto';
|
||||
|
||||
import { sr25519PairFromU8a } from './fromU8a';
|
||||
@@ -16,7 +16,9 @@ import { sr25519PairFromU8a } from './fromU8a';
|
||||
export function sr25519PairFromSeed (seed: HexString | Uint8Array | string): Keypair {
|
||||
const seedU8a = u8aToU8a(seed);
|
||||
|
||||
assert(seedU8a.length === 32, () => `Expected a seed matching 32 bytes, found ${seedU8a.length}`);
|
||||
if (seedU8a.length !== 32) {
|
||||
throw new Error(`Expected a seed matching 32 bytes, found ${seedU8a.length}`);
|
||||
}
|
||||
|
||||
return sr25519PairFromU8a(
|
||||
sr25519KeypairFromSeed(seedU8a)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Keypair } from '../../types';
|
||||
|
||||
import { assert, u8aToU8a } from '@polkadot/util';
|
||||
import { u8aToU8a } from '@polkadot/util';
|
||||
|
||||
const SEC_LEN = 64;
|
||||
const PUB_LEN = 32;
|
||||
@@ -13,7 +13,9 @@ const TOT_LEN = SEC_LEN + PUB_LEN;
|
||||
export function sr25519PairFromU8a (full: HexString | Uint8Array | string): Keypair {
|
||||
const fullU8a = u8aToU8a(full);
|
||||
|
||||
assert(fullU8a.length === TOT_LEN, () => `Expected keypair with ${TOT_LEN} bytes, found ${fullU8a.length}`);
|
||||
if (fullU8a.length !== TOT_LEN) {
|
||||
throw new Error(`Expected keypair with ${TOT_LEN} bytes, found ${fullU8a.length}`);
|
||||
}
|
||||
|
||||
return {
|
||||
publicKey: fullU8a.slice(SEC_LEN, TOT_LEN),
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Keypair } from '../types';
|
||||
|
||||
import { assert, u8aToU8a } from '@polkadot/util';
|
||||
import { u8aToU8a } from '@polkadot/util';
|
||||
import { sr25519Sign as wasmSign } from '@polkadot/wasm-crypto';
|
||||
|
||||
/**
|
||||
@@ -12,8 +12,11 @@ import { sr25519Sign as wasmSign } from '@polkadot/wasm-crypto';
|
||||
* @description Returns message signature of `message`, using the supplied pair
|
||||
*/
|
||||
export function sr25519Sign (message: HexString | Uint8Array | string, { publicKey, secretKey }: Partial<Keypair>): Uint8Array {
|
||||
assert(publicKey?.length === 32, 'Expected a valid publicKey, 32-bytes');
|
||||
assert(secretKey?.length === 64, 'Expected a valid secretKey, 64-bytes');
|
||||
if (publicKey?.length !== 32) {
|
||||
throw new Error('Expected a valid publicKey, 32-bytes');
|
||||
} else if (secretKey?.length !== 64) {
|
||||
throw new Error('Expected a valid secretKey, 64-bytes');
|
||||
}
|
||||
|
||||
return wasmSign(publicKey, secretKey, u8aToU8a(message));
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
|
||||
import { assert, u8aToU8a } from '@polkadot/util';
|
||||
import { u8aToU8a } from '@polkadot/util';
|
||||
import { sr25519Verify as wasmVerify } from '@polkadot/wasm-crypto';
|
||||
|
||||
/**
|
||||
@@ -14,8 +14,11 @@ export function sr25519Verify (message: HexString | Uint8Array | string, signatu
|
||||
const publicKeyU8a = u8aToU8a(publicKey);
|
||||
const signatureU8a = u8aToU8a(signature);
|
||||
|
||||
assert(publicKeyU8a.length === 32, () => `Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
|
||||
assert(signatureU8a.length === 64, () => `Invalid signature, received ${signatureU8a.length} bytes, expected 64`);
|
||||
if (publicKeyU8a.length !== 32) {
|
||||
throw new Error(`Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
|
||||
} else if (signatureU8a.length !== 64) {
|
||||
throw new Error(`Invalid signature, received ${signatureU8a.length} bytes, expected 64`);
|
||||
}
|
||||
|
||||
return wasmVerify(signatureU8a, u8aToU8a(message), publicKeyU8a);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
import type { Keypair } from '../types';
|
||||
|
||||
import { assert, u8aToU8a } from '@polkadot/util';
|
||||
import { u8aToU8a } from '@polkadot/util';
|
||||
import { vrfSign } from '@polkadot/wasm-crypto';
|
||||
|
||||
const EMPTY_U8A = new Uint8Array();
|
||||
@@ -14,7 +14,9 @@ const EMPTY_U8A = new Uint8Array();
|
||||
* @description Sign with sr25519 vrf signing (deterministic)
|
||||
*/
|
||||
export function sr25519VrfSign (message: HexString | Uint8Array | string, { secretKey }: Partial<Keypair>, context: HexString | string | Uint8Array = EMPTY_U8A, extra: HexString | string | Uint8Array = EMPTY_U8A): Uint8Array {
|
||||
assert(secretKey?.length === 64, 'Invalid secretKey, expected 64-bytes');
|
||||
if (secretKey?.length !== 64) {
|
||||
throw new Error('Invalid secretKey, expected 64-bytes');
|
||||
}
|
||||
|
||||
return vrfSign(secretKey, u8aToU8a(context), u8aToU8a(message), u8aToU8a(extra));
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import type { HexString } from '@polkadot/util/types';
|
||||
|
||||
import { assert, u8aToU8a } from '@polkadot/util';
|
||||
import { u8aToU8a } from '@polkadot/util';
|
||||
import { vrfVerify } from '@polkadot/wasm-crypto';
|
||||
|
||||
const EMPTY_U8A = new Uint8Array();
|
||||
@@ -16,8 +16,11 @@ export function sr25519VrfVerify (message: HexString | Uint8Array | string, sign
|
||||
const publicKeyU8a = u8aToU8a(publicKey);
|
||||
const proofU8a = u8aToU8a(signOutput);
|
||||
|
||||
assert(publicKeyU8a.length === 32, 'Invalid publicKey, expected 32-bytes');
|
||||
assert(proofU8a.length === 96, 'Invalid vrfSign output, expected 96 bytes');
|
||||
if (publicKeyU8a.length !== 32) {
|
||||
throw new Error('Invalid publicKey, expected 32-bytes');
|
||||
} else if (proofU8a.length !== 96) {
|
||||
throw new Error('Invalid vrfSign output, expected 96 bytes');
|
||||
}
|
||||
|
||||
return vrfVerify(publicKeyU8a, u8aToU8a(context), u8aToU8a(message), u8aToU8a(extra), proofU8a);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { arrayRange } from '@polkadot/util';
|
||||
import { performance, performanceCmp } from '@polkadot/util/test/performance';
|
||||
import { perf, perfCmp } from '@polkadot/util/test/performance';
|
||||
|
||||
import { randomAsU8a } from '..';
|
||||
|
||||
@@ -11,7 +11,7 @@ type ExecFn = (input: Uint8Array, onlyJs: boolean) => unknown;
|
||||
const GENERATED = arrayRange(256).map(() => [randomAsU8a()]);
|
||||
|
||||
export function performanceWasm (name: string, count: number, exec: ExecFn, inputs = GENERATED): void {
|
||||
performanceCmp(name, ['WebAssembly', 'JavaScript'], count, inputs, exec);
|
||||
perfCmp(name, ['WebAssembly', 'JavaScript'], count, inputs, exec);
|
||||
}
|
||||
|
||||
export { performance, performanceCmp };
|
||||
export { perf, perfCmp };
|
||||
|
||||
@@ -34,19 +34,19 @@
|
||||
"./detectPackage.cjs"
|
||||
],
|
||||
"type": "module",
|
||||
"version": "9.5.1",
|
||||
"version": "9.6.2",
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.18.3",
|
||||
"@polkadot/x-bigint": "9.5.1",
|
||||
"@polkadot/x-global": "9.5.1",
|
||||
"@polkadot/x-textdecoder": "9.5.1",
|
||||
"@polkadot/x-textencoder": "9.5.1",
|
||||
"@polkadot/x-bigint": "9.6.2",
|
||||
"@polkadot/x-global": "9.6.2",
|
||||
"@polkadot/x-textdecoder": "9.6.2",
|
||||
"@polkadot/x-textencoder": "9.6.2",
|
||||
"@types/bn.js": "^5.1.0",
|
||||
"bn.js": "^5.2.1",
|
||||
"ip-regex": "^4.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/x-randomvalues": "9.5.1"
|
||||
"@polkadot/x-randomvalues": "9.6.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { arrayChunk, arrayRange } from '.';
|
||||
|
||||
describe('arrayChunk', (): void => {
|
||||
@@ -11,5 +11,5 @@ describe('arrayChunk', (): void => {
|
||||
).toEqual([[1, 2, 3], [4, 5, 6], [7]]);
|
||||
});
|
||||
|
||||
performance('arrayChunk', 200_000, [[arrayRange(500), 50]], arrayChunk);
|
||||
perf('arrayChunk', 200_000, [[arrayRange(500), 50]], arrayChunk);
|
||||
});
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { isNull } from '../is/null';
|
||||
import { isUndefined } from '../is/undefined';
|
||||
|
||||
/**
|
||||
* @name arrayFilter
|
||||
* @summary Filters undefined and (optionally) null values from an array
|
||||
@@ -21,7 +18,7 @@ import { isUndefined } from '../is/undefined';
|
||||
*/
|
||||
export function arrayFilter <T = unknown> (array: (T | null | undefined)[], allowNulls = true): T[] {
|
||||
return array.filter((v): v is T =>
|
||||
!isUndefined(v) &&
|
||||
(allowNulls || !isNull(v))
|
||||
v !== undefined &&
|
||||
(allowNulls || v !== null)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { arrayRange, arrayShuffle } from '.';
|
||||
|
||||
const ptest = arrayRange(16284);
|
||||
@@ -32,5 +32,5 @@ describe('arrayShuffle', (): void => {
|
||||
).not.toEqual(JSON.stringify(out));
|
||||
});
|
||||
|
||||
performance('arrayShuffle', 1000, [[ptest]], arrayShuffle);
|
||||
perf('arrayShuffle', 1000, [[ptest]], arrayShuffle);
|
||||
});
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { isFunction } from './is/function';
|
||||
import { isNull } from './is/null';
|
||||
import { isUndefined } from './is/undefined';
|
||||
|
||||
type MessageFn = () => string;
|
||||
|
||||
@@ -38,7 +36,7 @@ export function assert (condition: unknown, message: string | MessageFn): assert
|
||||
* @description Returns when the value is not undefined/null, otherwise throws assertion error
|
||||
*/
|
||||
export function assertReturn <T> (value: T | undefined | null, message: string | MessageFn): T {
|
||||
assert(!isUndefined(value) && !isNull(value), message);
|
||||
assert(value !== undefined && value !== null, message);
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { arrayRange } from '../array';
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { nToU8a } from '.';
|
||||
|
||||
const ptest = arrayRange(65536).map((v) => [v]);
|
||||
@@ -56,5 +56,5 @@ describe('nToU8a', (): void => {
|
||||
).toEqual(new Uint8Array([46, 251, 255, 255]));
|
||||
});
|
||||
|
||||
performance('nToU8a', 250000, ptest, nToU8a);
|
||||
perf('nToU8a', 250000, ptest, nToU8a);
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { arrayRange } from '../array';
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { BN, bnToU8a } from '.';
|
||||
|
||||
const ptest = arrayRange(65536).map((v) => [v]);
|
||||
@@ -108,5 +108,5 @@ describe('bnToU8a', (): void => {
|
||||
});
|
||||
});
|
||||
|
||||
performance('bnToU8a', 250000, ptest, bnToU8a);
|
||||
perf('bnToU8a', 250000, ptest, bnToU8a);
|
||||
});
|
||||
|
||||
@@ -13,6 +13,7 @@ export * from './bn';
|
||||
export * from './buffer';
|
||||
export * from './compact';
|
||||
export * from './extractTime';
|
||||
export * from './float';
|
||||
export * from './format';
|
||||
export * from './has';
|
||||
export * from './hex';
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import { BN } from '../bn/bn';
|
||||
import { hexToU8a } from '../hex/toU8a';
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { compactFromU8a, compactFromU8aLim } from '.';
|
||||
|
||||
describe('compactFromU8a', (): void => {
|
||||
@@ -73,10 +73,10 @@ describe('compactFromU8a', (): void => {
|
||||
).toEqual('100000000');
|
||||
});
|
||||
|
||||
performance('compactFromU8a (u8)', 1_000_000, [[new Uint8Array([63 << 2])]], compactFromU8a);
|
||||
performance('compactFromU8a (u16)', 1_000_000, [[new Uint8Array([0b11111101, 0b00000111])]], compactFromU8a);
|
||||
performance('compactFromU8a (u32)', 1_000_000, [[new Uint8Array([254, 255, 3, 0])]], compactFromU8a);
|
||||
performance('compactFromU8aLim (u32)', 1_000_000, [[new Uint8Array([254, 255, 3, 0])]], compactFromU8aLim);
|
||||
performance('compactFromU8a (u48)', 1_000_000, [[hexToU8a('0x0b00407a10f35a')]], compactFromU8a);
|
||||
performance('compactFromU8a (u96)', 250_000, [[new Uint8Array([23, 52, 0x40, 0x7a, 0x10, 0xf3, 0x5a, 0, 0, 18])]], compactFromU8a);
|
||||
perf('compactFromU8a (u8)', 1_000_000, [[new Uint8Array([63 << 2])]], compactFromU8a);
|
||||
perf('compactFromU8a (u16)', 1_000_000, [[new Uint8Array([0b11111101, 0b00000111])]], compactFromU8a);
|
||||
perf('compactFromU8a (u32)', 1_000_000, [[new Uint8Array([254, 255, 3, 0])]], compactFromU8a);
|
||||
perf('compactFromU8aLim (u32)', 1_000_000, [[new Uint8Array([254, 255, 3, 0])]], compactFromU8aLim);
|
||||
perf('compactFromU8a (u48)', 1_000_000, [[hexToU8a('0x0b00407a10f35a')]], compactFromU8a);
|
||||
perf('compactFromU8a (u96)', 250_000, [[new Uint8Array([23, 52, 0x40, 0x7a, 0x10, 0xf3, 0x5a, 0, 0, 18])]], compactFromU8a);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export { floatToU8a } from './toU8a';
|
||||
@@ -0,0 +1,90 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { u8aToHex } from '../u8a';
|
||||
import { floatToU8a } from '.';
|
||||
|
||||
describe('floatToU8a', (): void => {
|
||||
it('throws on invalid bitLength', (): void => {
|
||||
expect(
|
||||
() => floatToU8a(123, { bitLength: 48 as 32 })
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
describe('32-bit', (): void => {
|
||||
it('correctly encodes +0.0', (): void => {
|
||||
expect(
|
||||
u8aToHex(floatToU8a(+0.0))
|
||||
).toEqual('0x00000000');
|
||||
});
|
||||
|
||||
it('correctly encodes -0.0', (): void => {
|
||||
expect(
|
||||
u8aToHex(floatToU8a(-0.0))
|
||||
).toEqual('0x00000080');
|
||||
});
|
||||
|
||||
it('correctly encodes -0.0 (BE)', (): void => {
|
||||
expect(
|
||||
u8aToHex(floatToU8a(-0.0, { isLe: false }))
|
||||
).toEqual('0x80000000');
|
||||
});
|
||||
|
||||
it('encodes NaN', (): void => {
|
||||
expect(
|
||||
u8aToHex(floatToU8a(Number.NaN, { isLe: true }))
|
||||
).toEqual('0x0000c07f');
|
||||
});
|
||||
|
||||
describe('equivalency', (): void => {
|
||||
it('encodes number 123.456', (): void => {
|
||||
expect(
|
||||
u8aToHex(floatToU8a(123.456))
|
||||
).toEqual('0x79e9f642');
|
||||
});
|
||||
|
||||
it('encodes string 123.456', (): void => {
|
||||
expect(
|
||||
u8aToHex(floatToU8a('123.456'))
|
||||
).toEqual('0x79e9f642');
|
||||
});
|
||||
|
||||
it('encodes Number 123.456', (): void => {
|
||||
class Test extends Number {
|
||||
foo = 'bar';
|
||||
}
|
||||
|
||||
// https://www.h-schmidt.net/FloatConverter/IEEE754.html
|
||||
expect(
|
||||
u8aToHex(floatToU8a(new Test(123.456)))
|
||||
).toEqual('0x79e9f642');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('64-bit', (): void => {
|
||||
it('correctly encodes +0.0', (): void => {
|
||||
expect(
|
||||
u8aToHex(floatToU8a(+0.0, { bitLength: 64 }))
|
||||
).toEqual('0x0000000000000000');
|
||||
});
|
||||
|
||||
it('correctly encodes -0.0', (): void => {
|
||||
expect(
|
||||
u8aToHex(floatToU8a(-0.0, { bitLength: 64, isLe: true }))
|
||||
).toEqual('0x0000000000000080');
|
||||
});
|
||||
|
||||
it('correctly encodes -0.0 (BE)', (): void => {
|
||||
expect(
|
||||
u8aToHex(floatToU8a(-0.0, { bitLength: 64, isLe: false }))
|
||||
).toEqual('0x8000000000000000');
|
||||
});
|
||||
|
||||
it('encodes NaN', (): void => {
|
||||
expect(
|
||||
u8aToHex(floatToU8a(Number.NaN, { bitLength: 64 }))
|
||||
).toEqual('0x000000000000f87f');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
type AnyFloat = number | Number;
|
||||
|
||||
interface Options {
|
||||
bitLength?: 32 | 64;
|
||||
isLe?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* @name floatToU8a
|
||||
* @description Converts a float into a U8a representation (While we don't use BE in SCALE
|
||||
* we still allow for either representation, although, as elsewhere, isLe is default)
|
||||
*/
|
||||
export function floatToU8a (value: string | AnyFloat = 0.0, { bitLength = 32, isLe = true }: Options = {}): Uint8Array {
|
||||
if (bitLength !== 32 && bitLength !== 64) {
|
||||
throw new Error('Invalid bitLength provided, expected 32 or 64');
|
||||
}
|
||||
|
||||
const result = new Uint8Array(bitLength / 8);
|
||||
const dv = new DataView(result.buffer, result.byteOffset);
|
||||
|
||||
if (bitLength === 32) {
|
||||
dv.setFloat32(0, Number(value), isLe);
|
||||
} else {
|
||||
dv.setFloat64(0, Number(value), isLe);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import type { SiDef, ToBn } from '../types';
|
||||
|
||||
import { bnToBn } from '../bn/toBn';
|
||||
import { isBoolean } from '../is/boolean';
|
||||
import { isUndefined } from '../is/undefined';
|
||||
import { formatDecimal } from './formatDecimal';
|
||||
import { calcSi, findSi, SI, SI_MID } from './si';
|
||||
|
||||
@@ -147,12 +146,12 @@ formatBalance.getOptions = (decimals: number = defaultDecimals): SiDef[] => {
|
||||
// Sets the default decimals to use for formatting (ui-wide)
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
formatBalance.setDefaults = ({ decimals, unit }: SetDefaults): void => {
|
||||
defaultDecimals = isUndefined(decimals)
|
||||
defaultDecimals = decimals === undefined
|
||||
? defaultDecimals
|
||||
: Array.isArray(decimals)
|
||||
? decimals[0]
|
||||
: decimals;
|
||||
defaultUnit = isUndefined(unit)
|
||||
defaultUnit = unit === undefined
|
||||
? defaultUnit
|
||||
: Array.isArray(unit)
|
||||
? unit[0]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { performanceCmp } from '../test/performance';
|
||||
import { perfCmp } from '../test/performance';
|
||||
import { hexToU8a as hexToU8aBuffer } from './toU8aBuffer';
|
||||
import { hexToU8a } from '.';
|
||||
|
||||
@@ -18,6 +18,12 @@ describe('hexToU8a', (): void => {
|
||||
).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('returns an empty Uint8Array when 0x provided', (): void => {
|
||||
expect(
|
||||
hexToU8a('0x')
|
||||
).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('returns a Uint8Array with the correct values', (): void => {
|
||||
expect(
|
||||
hexToU8a('0x80000a')
|
||||
@@ -54,7 +60,7 @@ describe('hexToU8a', (): void => {
|
||||
).toThrow(/hex value to convert/);
|
||||
});
|
||||
|
||||
performanceCmp('hexToU8a', ['hexToU8aBuffer', 'hexToU8a'], 20, [[ptest]], (s: string, isSecond) =>
|
||||
perfCmp('hexToU8a', ['hexToU8aBuffer', 'hexToU8a'], 25, [[ptest]], (s: string, isSecond) =>
|
||||
isSecond
|
||||
? hexToU8a(s)
|
||||
: hexToU8aBuffer(s)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import type { HexString } from '../types';
|
||||
|
||||
import { hexStripPrefix } from './stripPrefix';
|
||||
import { REGEX_HEX_NOPREFIX, REGEX_HEX_PREFIXED } from '../is/hex';
|
||||
|
||||
const CHARS = '0123456789abcdef';
|
||||
const UNHEX = new Array<number>(256);
|
||||
@@ -32,12 +32,22 @@ for (let i = 0; i < CHARS.length; i++) {
|
||||
* ```
|
||||
*/
|
||||
export function hexToU8a (value?: HexString | string | null, bitLength = -1): Uint8Array {
|
||||
if (!value) {
|
||||
if (!value || value === '0x') {
|
||||
return new Uint8Array();
|
||||
}
|
||||
|
||||
const str = hexStripPrefix(value);
|
||||
const strLength = str.length / 2;
|
||||
let s = 0;
|
||||
|
||||
// we don't use hexStringPrefix here - that has substring which adds
|
||||
// additional overhead. Instead we duplicate the logic, just incrementing
|
||||
// the sactual string pointer, ignoring the prefix as required
|
||||
if (REGEX_HEX_PREFIXED.test(value)) {
|
||||
s = 2;
|
||||
} else if (!REGEX_HEX_NOPREFIX.test(value)) {
|
||||
throw new Error(`Expected hex value to convert, found '${value}'`);
|
||||
}
|
||||
|
||||
const strLength = (value.length - s) / 2;
|
||||
const endLength = Math.ceil(
|
||||
bitLength === -1
|
||||
? strLength
|
||||
@@ -48,12 +58,12 @@ export function hexToU8a (value?: HexString | string | null, bitLength = -1): Ui
|
||||
? endLength - strLength
|
||||
: 0;
|
||||
|
||||
for (let i = offset, s = 0; i < endLength; i++, s += 2) {
|
||||
for (let i = offset; i < endLength; i++, s += 2) {
|
||||
// The big factor here is actually the string lookups. If we do
|
||||
// HEX_TO_U16[value.substring()] we get an 10x slowdown. In the
|
||||
// same vein using charCodeAt (as opposed to value[s] or value.charAt(s)) is
|
||||
// also the faster operation by at least 2x with the character map above
|
||||
result[i] = ((UNHEX[str.charCodeAt(s)] << 4) + UNHEX[str.charCodeAt(s + 1)]) | 0;
|
||||
result[i] = (UNHEX[value.charCodeAt(s)] << 4) + UNHEX[value.charCodeAt(s + 1)];
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { performance } from '../test/performance';
|
||||
import { stringToU8a } from '../string';
|
||||
import { perf } from '../test/performance';
|
||||
import { isAscii } from '.';
|
||||
|
||||
describe('isAscii', (): void => {
|
||||
@@ -37,5 +38,6 @@ describe('isAscii', (): void => {
|
||||
expect(isAscii('0x010203')).toEqual(false);
|
||||
});
|
||||
|
||||
performance('isAscii', 100_000, [[[0x31, 0x32, 0x20, 10, 9, 13, 65, 66, 67, 68, 69, 70]]], isAscii);
|
||||
perf('isAscii (str)', 2_000_000, [['Hello\tWorld!\n\rTesting']], isAscii);
|
||||
perf('isAscii (u8a)', 200_000, [[[stringToU8a('Hello\tWorld!\n\rTesting')]]], isAscii);
|
||||
});
|
||||
|
||||
@@ -24,7 +24,7 @@ function isAsciiStr (str: AnyString): boolean {
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function isAsciiU8a (u8a: Uint8Array): boolean {
|
||||
function isAsciiBytes (u8a: Uint8Array | Buffer | number[]): boolean {
|
||||
const count = u8a.length;
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
@@ -46,9 +46,11 @@ function isAsciiU8a (u8a: Uint8Array): boolean {
|
||||
* Checks to see if the input string or Uint8Array is printable ASCII, 32-127 + formatters
|
||||
*/
|
||||
export function isAscii (value?: U8aLike | null): boolean {
|
||||
return isString(value) && !isHex(value)
|
||||
? isAsciiStr(value)
|
||||
return isString(value)
|
||||
? isHex(value)
|
||||
? isAsciiBytes(u8aToU8a(value))
|
||||
: isAsciiStr(value)
|
||||
: value
|
||||
? isAsciiU8a(u8aToU8a(value))
|
||||
? isAsciiBytes(value)
|
||||
: false;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { performanceCmp } from '../test/performance';
|
||||
import { perfCmp } from '../test/performance';
|
||||
import { isCodec } from '.';
|
||||
|
||||
const ptest = {
|
||||
@@ -47,7 +47,7 @@ describe('isCodec', (): void => {
|
||||
).toEqual(false);
|
||||
});
|
||||
|
||||
performanceCmp('isCodec', ['isCodec', 'instanceof'], 500_000, [[ptest]], (v: unknown, isSecond) =>
|
||||
perfCmp('isCodec', ['isCodec', 'instanceof'], 500_000, [[ptest]], (v: unknown, isSecond) =>
|
||||
isSecond
|
||||
? !(v instanceof String)
|
||||
: isCodec(v)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { isHex } from '.';
|
||||
|
||||
describe('isHex', (): void => {
|
||||
@@ -71,5 +71,5 @@ describe('isHex', (): void => {
|
||||
).toEqual(true);
|
||||
});
|
||||
|
||||
performance(`isHex (${(ptest.length - 2) / 2} bytes)`, 5000, [[ptest]], isHex);
|
||||
perf(`isHex (${(ptest.length - 2) / 2} bytes)`, 1000, [[ptest]], isHex);
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { isU8a } from '.';
|
||||
|
||||
describe('isU8a', (): void => {
|
||||
@@ -36,5 +36,5 @@ describe('isU8a', (): void => {
|
||||
).toEqual(true);
|
||||
});
|
||||
|
||||
performance('isU8a', 2_000_000, [[new Uint8Array()]], isU8a);
|
||||
perf('isU8a', 2_000_000, [[new Uint8Array()]], isU8a);
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { perf } from '../test/performance';
|
||||
import { isUndefined } from '.';
|
||||
|
||||
describe('isUndefined', (): void => {
|
||||
@@ -15,4 +16,6 @@ describe('isUndefined', (): void => {
|
||||
isUndefined(null)
|
||||
).toEqual(false);
|
||||
});
|
||||
|
||||
perf('isUndefined', 10_000_000, [[null]], isUndefined);
|
||||
});
|
||||
|
||||
@@ -17,5 +17,5 @@
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export function isUndefined (value?: unknown): value is undefined {
|
||||
return typeof value === 'undefined';
|
||||
return value === undefined;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
// Copyright 2017-2022 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { isUndefined } from './is/undefined';
|
||||
|
||||
type AnyFn = (...args: unknown[]) => unknown;
|
||||
|
||||
type WithToString = { toString: () => string };
|
||||
@@ -31,7 +29,7 @@ export function lazyMethod <T, K> (result: Record<string, T> | AnyFn, item: K, c
|
||||
// This check should _always_ be false and unneeded, since we override
|
||||
// with a value below ... however we ensure we are quire vigilant against
|
||||
// all environment failures, so we are rather be safe than sorry
|
||||
if (isUndefined(value)) {
|
||||
if (value === undefined) {
|
||||
value = creator(item);
|
||||
|
||||
try {
|
||||
|
||||
@@ -142,7 +142,7 @@ function parseEnv (type: string): [boolean, number] {
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import { logger } from '@polkadot';
|
||||
* import { logger } from '@polkadot/util';
|
||||
*
|
||||
* const l = logger('test');
|
||||
* ```
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
|
||||
import type { Memoized } from './types';
|
||||
|
||||
import { isUndefined } from './is/undefined';
|
||||
import { stringify } from './stringify';
|
||||
|
||||
interface Options {
|
||||
@@ -30,7 +29,7 @@ export function memoize <T, F extends (...args: any[]) => T> (fn: F, { getInstan
|
||||
cache[instanceId] = {};
|
||||
}
|
||||
|
||||
if (isUndefined(cache[instanceId][stringParams])) {
|
||||
if (cache[instanceId][stringParams] === undefined) {
|
||||
cache[instanceId][stringParams] = fn(...args);
|
||||
}
|
||||
|
||||
@@ -41,7 +40,7 @@ export function memoize <T, F extends (...args: any[]) => T> (fn: F, { getInstan
|
||||
const stringParams = stringify(args);
|
||||
const instanceId = getInstanceId();
|
||||
|
||||
if (cache[instanceId] && !isUndefined(cache[instanceId][stringParams])) {
|
||||
if (cache[instanceId] && cache[instanceId][stringParams] !== undefined) {
|
||||
delete cache[instanceId][stringParams];
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export * from './index';
|
||||
@@ -4,8 +4,6 @@
|
||||
import type { HexString } from '../types';
|
||||
|
||||
import { hexFixLength } from '../hex/fixLength';
|
||||
import { isNull } from '../is/null';
|
||||
import { isUndefined } from '../is/undefined';
|
||||
|
||||
/**
|
||||
* @name numberToHex
|
||||
@@ -23,7 +21,7 @@ import { isUndefined } from '../is/undefined';
|
||||
* ```
|
||||
*/
|
||||
export function numberToHex (value?: number | null, bitLength = -1): HexString {
|
||||
if (isUndefined(value) || isNull(value) || isNaN(value)) {
|
||||
if (value === undefined || value === null || isNaN(value)) {
|
||||
return '0x';
|
||||
}
|
||||
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { hexToU8a } from '../hex/toU8a';
|
||||
import { isNull } from '../is/null';
|
||||
import { isUndefined } from '../is/undefined';
|
||||
import { numberToHex } from './toHex';
|
||||
|
||||
/**
|
||||
@@ -21,7 +19,7 @@ import { numberToHex } from './toHex';
|
||||
* ```
|
||||
*/
|
||||
export function numberToU8a (value?: number | null, bitLength = -1): Uint8Array {
|
||||
return isUndefined(value) || isNull(value) || isNaN(value)
|
||||
return value === undefined || value === null || isNaN(value)
|
||||
? new Uint8Array()
|
||||
: hexToU8a(
|
||||
numberToHex(value, bitLength)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { objectProperties, objectProperty } from '.';
|
||||
|
||||
describe('objectProperty/objectProperties', (): void => {
|
||||
@@ -142,6 +142,6 @@ describe('objectProperty/objectProperties', (): void => {
|
||||
expect(getter).toHaveBeenCalledWith('b', 1);
|
||||
});
|
||||
|
||||
performance('objectProperties (obj)', 50_000, [[]], () => objectProperties({}, ['foo', 'bar', 'baz'], (k) => k));
|
||||
performance('objectProperties (map)', 50_000, [[]], () => objectProperties(new Map(), ['foo', 'bar', 'baz'], (k) => k));
|
||||
perf('objectProperties (obj)', 50_000, [[]], () => objectProperties({}, ['foo', 'bar', 'baz'], (k) => k));
|
||||
perf('objectProperties (map)', 50_000, [[]], () => objectProperties(new Map(), ['foo', 'bar', 'baz'], (k) => k));
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { objectSpread } from '.';
|
||||
|
||||
describe('objectSpread', (): void => {
|
||||
@@ -17,5 +17,5 @@ describe('objectSpread', (): void => {
|
||||
).toEqual({ a: 2, b: 2, c: { d: 3, e: 4 } });
|
||||
});
|
||||
|
||||
performance('objectSpread', 500_000, [[]], () => objectSpread({}, { a: 1, b: 2, c: 3 }, { d: 4, e: 7, f: 6 }));
|
||||
perf('objectSpread', 500_000, [[]], () => objectSpread({}, { a: 1, b: 2, c: 3 }, { d: 4, e: 7, f: 6 }));
|
||||
});
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
|
||||
// Do not edit, auto-generated by @polkadot/dev
|
||||
|
||||
export const packageInfo = { name: '@polkadot/util', path: 'auto', type: 'auto', version: '9.5.1' };
|
||||
export const packageInfo = { name: '@polkadot/util', path: 'auto', type: 'auto', version: '9.6.2' };
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import { getRandomValues } from '@polkadot/x-randomvalues';
|
||||
|
||||
import { arrayRange } from '../array';
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { stringCamelCase, stringUpperFirst } from '.';
|
||||
|
||||
const SEPS = [' ', '_', '-', '.', ','];
|
||||
@@ -112,6 +112,6 @@ describe('stringCamelCase', (): void => {
|
||||
).toEqual('aBCDef');
|
||||
});
|
||||
|
||||
performance('stringCamelCase (random)', 100_000, randomWords, stringCamelCase);
|
||||
performance('stringCamelCase (NFTOrder)', 100_000, [['NFTOrder']], stringCamelCase);
|
||||
perf('stringCamelCase (random)', 100_000, randomWords, stringCamelCase);
|
||||
perf('stringCamelCase (NFTOrder)', 100_000, [['NFTOrder']], stringCamelCase);
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { stringLowerFirst } from '.';
|
||||
|
||||
describe('stringLowerFirst', (): void => {
|
||||
@@ -35,5 +35,5 @@ describe('stringLowerFirst', (): void => {
|
||||
).toBe('');
|
||||
});
|
||||
|
||||
performance('stringLowerFirst', 1_000_000, [['HelloWorldSomething']], stringLowerFirst);
|
||||
perf('stringLowerFirst', 1_000_000, [['HelloWorldSomething']], stringLowerFirst);
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { stringUpperFirst } from '.';
|
||||
|
||||
describe('stringUpperFirst', (): void => {
|
||||
@@ -35,5 +35,5 @@ describe('stringUpperFirst', (): void => {
|
||||
).toBe('');
|
||||
});
|
||||
|
||||
performance('stringUpperFirst', 1_000_000, [['helloWorldSomething']], stringUpperFirst);
|
||||
perf('stringUpperFirst', 1_000_000, [['helloWorldSomething']], stringUpperFirst);
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { formatDecimal, formatNumber } from '..';
|
||||
@@ -10,7 +10,7 @@ const NUM_PAD = 16;
|
||||
const PRE_PAD = 32;
|
||||
|
||||
function loop (count: number, inputs: unknown[][], exec: ExecFn): [number, unknown[]] {
|
||||
const start = Date.now();
|
||||
const start = performance.now();
|
||||
const results = new Array<unknown>(inputs.length);
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
@@ -21,7 +21,7 @@ function loop (count: number, inputs: unknown[][], exec: ExecFn): [number, unkno
|
||||
}
|
||||
}
|
||||
|
||||
return [Date.now() - start, results];
|
||||
return [performance.now() - start, results];
|
||||
}
|
||||
|
||||
export function formatFixed (value: number): string {
|
||||
@@ -39,19 +39,27 @@ ${formatFixed(ops).padStart(NUM_PAD + PRE_PAD + 1)} ops/s
|
||||
${formatFixed(micro).padStart(NUM_PAD + PRE_PAD + 1)} μs/op`;
|
||||
}
|
||||
|
||||
export function performance (name: string, count: number, inputs: unknown[][], exec: ExecFn): void {
|
||||
export function perf (name: string, count: number, inputs: unknown[][], exec: ExecFn): void {
|
||||
if (process.env.GITHUB_REPOSITORY) {
|
||||
return;
|
||||
}
|
||||
|
||||
it(`performance: ${name}`, (): void => {
|
||||
const [time] = loop(count, inputs, exec);
|
||||
|
||||
console.log(`
|
||||
performance run for ${name} completed with ${formatNumber(count)} iterations.
|
||||
|
||||
${`${name}:`.padStart(PRE_PAD)} ${time.toString().padStart(NUM_PAD)} ms${formatOps(count, time)}
|
||||
${`${name}:`.padStart(PRE_PAD)} ${time.toFixed(2).padStart(NUM_PAD)} ms${formatOps(count, time)}
|
||||
`);
|
||||
});
|
||||
}
|
||||
|
||||
export function performanceCmp (name: string, [first, second]: [string, string], count: number, inputs: unknown[][], exec: ExecFn): void {
|
||||
export function perfCmp (name: string, [first, second]: [string, string], count: number, inputs: unknown[][], exec: ExecFn): void {
|
||||
if (process.env.GITHUB_REPOSITORY) {
|
||||
return;
|
||||
}
|
||||
|
||||
it(`performance: ${name}`, (): void => {
|
||||
const pa = inputs.map((values) => [...values, false]);
|
||||
const pb = inputs.map((values) => [...values, true]);
|
||||
@@ -61,9 +69,9 @@ export function performanceCmp (name: string, [first, second]: [string, string],
|
||||
console.log(`
|
||||
performance run for ${name} completed with ${formatNumber(count)} iterations.
|
||||
|
||||
${`${first}:`.padStart(PRE_PAD)} ${ta.toString().padStart(NUM_PAD)} ms ${ta < tb ? '(fastest)' : `(slowest, ${(ta / tb).toFixed(2)}x)`}${formatOps(count, ta)}
|
||||
${`${first}:`.padStart(PRE_PAD)} ${ta.toFixed(2).padStart(NUM_PAD)} ms ${ta < tb ? '(fastest)' : `(slowest, ${(ta / tb).toFixed(2)}x)`}${formatOps(count, ta)}
|
||||
|
||||
${`${second}:`.padStart(PRE_PAD)} ${tb.toString().padStart(NUM_PAD)} ms ${ta > tb ? '(fastest)' : `(slowest, ${(tb / ta).toFixed(2)}x)`}${formatOps(count, tb)}
|
||||
${`${second}:`.padStart(PRE_PAD)} ${tb.toFixed(2).padStart(NUM_PAD)} ms ${ta > tb ? '(fastest)' : `(slowest, ${(tb / ta).toFixed(2)}x)`}${formatOps(count, tb)}
|
||||
`);
|
||||
|
||||
const unmatched = ra.filter((r, i) =>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import { getRandomValues } from '@polkadot/x-randomvalues';
|
||||
|
||||
import { arrayRange } from '../array';
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { u8aConcat, u8aConcatStrict } from '.';
|
||||
|
||||
const ptest = arrayRange(10).map(() => getRandomValues(new Uint8Array(32)));
|
||||
@@ -34,7 +34,7 @@ describe('u8aConcat', (): void => {
|
||||
);
|
||||
});
|
||||
|
||||
performance('u8aConcat', 10000, [[ptest]], u8aConcat);
|
||||
performance('u8aConcatStrict', 10000, [[[ptest]]], u8aConcatStrict);
|
||||
performance('u8aConcatStrict (len)', 10000, [[[ptest], 320]], u8aConcatStrict);
|
||||
perf('u8aConcat', 10000, [[ptest]], u8aConcat);
|
||||
perf('u8aConcatStrict', 10000, [[[ptest]]], u8aConcatStrict);
|
||||
perf('u8aConcatStrict (len)', 10000, [[[ptest], 320]], u8aConcatStrict);
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { u8aEmpty } from '.';
|
||||
|
||||
const ztest = new Uint8Array(32);
|
||||
@@ -25,5 +25,5 @@ describe('u8aEmpty', (): void => {
|
||||
).toEqual(false);
|
||||
});
|
||||
|
||||
performance('u8aEmpty (32 cmp)', 1000000, [[ztest]], u8aEmpty);
|
||||
perf('u8aEmpty (32 cmp)', 1000000, [[ztest]], u8aEmpty);
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { u8aEq } from '.';
|
||||
|
||||
const ltest = new Uint8Array(32768);
|
||||
@@ -105,7 +105,7 @@ describe('u8aEq', (): void => {
|
||||
).toEqual(true);
|
||||
});
|
||||
|
||||
performance('u8aEq (64 cmp)', 200_000, [[ztest, ztest]], u8aEq);
|
||||
performance('u8aEq (256 cmp)', 200_000, [[stest, stest]], u8aEq);
|
||||
performance('u8aEq (32k cmp)', 10_000, [[ltest, ltest]], u8aEq);
|
||||
perf('u8aEq (64 cmp)', 200_000, [[ztest, ztest]], u8aEq);
|
||||
perf('u8aEq (256 cmp)', 200_000, [[stest, stest]], u8aEq);
|
||||
perf('u8aEq (32k cmp)', 10_000, [[ltest, ltest]], u8aEq);
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ export { u8aConcat, u8aConcatStrict } from './concat';
|
||||
export { u8aEmpty } from './empty';
|
||||
export { u8aEq } from './eq';
|
||||
export { u8aFixLength } from './fixLength';
|
||||
export { u8aToFloat } from './toFloat';
|
||||
export { u8aSorted } from './sorted';
|
||||
export { u8aToBigInt } from './toBigInt';
|
||||
export { u8aToBn } from './toBn';
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { u8aToBigInt } from '.';
|
||||
|
||||
describe('u8aToBigInt', (): void => {
|
||||
@@ -58,5 +58,5 @@ describe('u8aToBigInt', (): void => {
|
||||
).toEqual(-1234n);
|
||||
});
|
||||
|
||||
performance('u8aToBigInt', 500000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c])]], u8aToBigInt);
|
||||
perf('u8aToBigInt', 500000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c])]], u8aToBigInt);
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { u8aToBn } from '.';
|
||||
|
||||
describe('u8aToBn', (): void => {
|
||||
@@ -299,7 +299,7 @@ describe('u8aToBn', (): void => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
performance('u8aToBn (u32)', 1_000_000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c])]], u8aToBn);
|
||||
performance('u8aToBn (i32)', 1_000_000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c])]], (v: Uint8Array) => u8aToBn(v, { isNegative: true }));
|
||||
performance('u8aToBn (u64)', 500_000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x68, 0x65, 0x6c, 0x6c])]], u8aToBn);
|
||||
perf('u8aToBn (u32)', 1_000_000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c])]], u8aToBn);
|
||||
perf('u8aToBn (i32)', 1_000_000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c])]], (v: Uint8Array) => u8aToBn(v, { isNegative: true }));
|
||||
perf('u8aToBn (u64)', 500_000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x68, 0x65, 0x6c, 0x6c])]], u8aToBn);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { hexToU8a } from '../hex';
|
||||
import { u8aToFloat } from '.';
|
||||
|
||||
describe('u8aToFloat', (): void => {
|
||||
it('throws on invalid bitLength', (): void => {
|
||||
expect(
|
||||
() => u8aToFloat(hexToU8a('0x00000000'), { bitLength: 48 as 32 })
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it('throws on invalid input length', (): void => {
|
||||
expect(
|
||||
() => u8aToFloat(new Uint8Array())
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
describe('32-bit', (): void => {
|
||||
it('correctly decodes +0.0', (): void => {
|
||||
expect(
|
||||
u8aToFloat(hexToU8a('0x00000000'))
|
||||
).toEqual(+0.0);
|
||||
});
|
||||
|
||||
it('correctly decodes -0.0', (): void => {
|
||||
expect(
|
||||
u8aToFloat(hexToU8a('0x00000080'))
|
||||
).toEqual(-0.0);
|
||||
});
|
||||
|
||||
it('correctly decodes -0.0 (BE)', (): void => {
|
||||
expect(
|
||||
u8aToFloat(hexToU8a('0x80000000'), { isLe: false })
|
||||
).toEqual(-0.0);
|
||||
});
|
||||
|
||||
it('decoded NaN', (): void => {
|
||||
expect(
|
||||
u8aToFloat(hexToU8a('0x0000c07f'))
|
||||
).toEqual(Number.NaN);
|
||||
});
|
||||
|
||||
// https://www.h-schmidt.net/FloatConverter/IEEE754.html
|
||||
it('decodes a known number', (): void => {
|
||||
expect(
|
||||
u8aToFloat(hexToU8a('0x79e9f642')).toFixed(3)
|
||||
).toEqual('123.456');
|
||||
});
|
||||
|
||||
it('decodes a known number (BE)', (): void => {
|
||||
expect(
|
||||
u8aToFloat(hexToU8a('0x42f6e979'), { isLe: false }).toFixed(3)
|
||||
).toEqual('123.456');
|
||||
});
|
||||
});
|
||||
|
||||
describe('64-bit', (): void => {
|
||||
it('correctly decodes +0.0', (): void => {
|
||||
expect(
|
||||
u8aToFloat(hexToU8a('0x0000000000000000'), { bitLength: 64 })
|
||||
).toEqual(+0.0);
|
||||
});
|
||||
|
||||
it('correctly decodes -0.0', (): void => {
|
||||
expect(
|
||||
u8aToFloat(hexToU8a('0x0000000000000080'), { bitLength: 64 })
|
||||
).toEqual(-0.0);
|
||||
});
|
||||
|
||||
it('correctly decodes -0.0 (BE)', (): void => {
|
||||
expect(
|
||||
u8aToFloat(hexToU8a('0x8000000000000000'), { bitLength: 64, isLe: false })
|
||||
).toEqual(-0.0);
|
||||
});
|
||||
|
||||
it('correctly decodes NaN', (): void => {
|
||||
expect(
|
||||
u8aToFloat(hexToU8a('0x000000000000f87f'), { bitLength: 64 })
|
||||
).toEqual(Number.NaN);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
interface Options {
|
||||
bitLength?: 32 | 64;
|
||||
isLe?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* @name u8aToFloat
|
||||
* @description Converts a Uint8Array value into the float (either 32 or 64-bit)
|
||||
* representation.
|
||||
*/
|
||||
export function u8aToFloat (value: Uint8Array, { bitLength = 32, isLe = true }: Options = {}): number {
|
||||
if (bitLength !== 32 && bitLength !== 64) {
|
||||
throw new Error('Invalid bitLength provided, expected 32 or 64');
|
||||
} else if (value.length < (bitLength / 8)) {
|
||||
throw new Error(`Invalid input buffer provided, expected at least ${bitLength / 8} bytes, found ${value.length}`);
|
||||
}
|
||||
|
||||
const dv = new DataView(value.buffer, value.byteOffset);
|
||||
|
||||
return bitLength === 32
|
||||
? dv.getFloat32(0, isLe)
|
||||
: dv.getFloat64(0, isLe);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { performanceCmp } from '../test/performance';
|
||||
import { perfCmp } from '../test/performance';
|
||||
import { u8aToHex as u8aToHexBuffer } from './toHexBuffer';
|
||||
import { u8aToHex } from '.';
|
||||
|
||||
@@ -78,12 +78,12 @@ describe('u8aToHex', (): void => {
|
||||
).toEqual('0x68656c6c6f20776f726c64');
|
||||
});
|
||||
|
||||
performanceCmp('u8aToHex (32k)', ['u8aToHexBuffer', 'u8aToHex'], 2000, [[ptest32k]], (s: Uint8Array, isSecond) =>
|
||||
perfCmp('u8aToHex (32k)', ['u8aToHexBuffer', 'u8aToHex'], 2000, [[ptest32k]], (s: Uint8Array, isSecond) =>
|
||||
isSecond
|
||||
? u8aToHex(s)
|
||||
: u8aToHexBuffer(s)
|
||||
);
|
||||
performanceCmp('u8aToHex (128)', ['u8aToHexBuffer', 'u8aToHex'], 100000, [[ptest256]], (s: Uint8Array, isSecond) =>
|
||||
perfCmp('u8aToHex (128)', ['u8aToHexBuffer', 'u8aToHex'], 100000, [[ptest256]], (s: Uint8Array, isSecond) =>
|
||||
isSecond
|
||||
? u8aToHex(s)
|
||||
: u8aToHexBuffer(s)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { u8aToNumber } from '.';
|
||||
|
||||
describe('u8aToNumber', (): void => {
|
||||
@@ -130,6 +130,6 @@ describe('u8aToNumber', (): void => {
|
||||
});
|
||||
});
|
||||
|
||||
performance('u8aToNumber (u32)', 1_000_000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c])]], u8aToNumber);
|
||||
performance('u8aToNumber (i32)', 1_000_000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c])]], (v: Uint8Array) => u8aToNumber(v, { isNegative: true }));
|
||||
perf('u8aToNumber (u32)', 1_000_000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c])]], u8aToNumber);
|
||||
perf('u8aToNumber (i32)', 1_000_000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c])]], (v: Uint8Array) => u8aToNumber(v, { isNegative: true }));
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2022 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { performance } from '../test/performance';
|
||||
import { perf } from '../test/performance';
|
||||
import { u8aToU8a } from '.';
|
||||
|
||||
describe('u8aToU8a', (): void => {
|
||||
@@ -70,7 +70,7 @@ describe('u8aToU8a', (): void => {
|
||||
).toEqual(new Uint8Array([49, 50, 51]));
|
||||
});
|
||||
|
||||
performance('u8aToU8a (hex)', 250_000, [['0x1234']], u8aToU8a);
|
||||
performance('u8aToU8a (str)', 250_000, [['test']], u8aToU8a);
|
||||
performance('u8aToU8a (u8a)', 1_000_000, [[new Uint8Array()]], u8aToU8a);
|
||||
perf('u8aToU8a (hex)', 250_000, [['0x1234']], u8aToU8a);
|
||||
perf('u8aToU8a (str)', 250_000, [['test']], u8aToU8a);
|
||||
perf('u8aToU8a (u8a)', 1_000_000, [[new Uint8Array()]], u8aToU8a);
|
||||
});
|
||||
|
||||
@@ -20,9 +20,9 @@
|
||||
"./shim.cjs"
|
||||
],
|
||||
"type": "module",
|
||||
"version": "9.5.1",
|
||||
"version": "9.6.2",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.18.3",
|
||||
"@polkadot/x-global": "9.5.1"
|
||||
"@polkadot/x-global": "9.6.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
// Copyright 2017-2022 @polkadot/x-bigint authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { xglobal } from '@polkadot/x-global';
|
||||
|
||||
export { packageInfo } from './packageInfo';
|
||||
|
||||
export const BigInt = xglobal.BigInt;
|
||||
@@ -3,4 +3,4 @@
|
||||
|
||||
// Do not edit, auto-generated by @polkadot/dev
|
||||
|
||||
export const packageInfo = { name: '@polkadot/x-bigint', path: 'auto', type: 'auto', version: '9.5.1' };
|
||||
export const packageInfo = { name: '@polkadot/x-bigint', path: 'auto', type: 'auto', version: '9.6.2' };
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user