Compare commits

...
42 Commits
Author SHA1 Message Date
github-actions[bot] 62182bae03 [CI Skip] release/stable 12.4.2
skip-checks: true
2023-08-23 09:55:33 +00:00
Jaco 2ee03a5f81 12.4.2 (#1872) 2023-08-23 12:48:09 +03:00
github-actions[bot] 7a5a88a135 [CI Skip] bump/beta 12.4.2-5-x
skip-checks: true
2023-08-23 09:09:55 +00:00
Jaco f4e0e2111f Extend u8aToBuffer check with hasBuffer (#1871)
* Extend u8aToBuffer check with hasBuffer

* CHANGELOG

* Always return Uint8Array

* New instance of fallback
2023-08-23 12:01:59 +03:00
github-actions[bot] aac902011e [CI Skip] bump/beta 12.4.2-4-x
skip-checks: true
2023-08-23 08:29:44 +00:00
Jaco a030330808 Additional test cleanups (#1870)
* Additional test cleanups

* More compact test loops

* Correct float expected values

* Adjust
2023-08-23 11:23:45 +03:00
github-actions[bot] d108beafd4 [CI Skip] bump/beta 12.4.2-3-x
skip-checks: true
2023-08-23 06:21:04 +00:00
Jaco 90e20ed4d2 Some small test loop cleanups (#1869) 2023-08-23 09:14:55 +03:00
github-actions[bot] 723ec10fa1 [CI Skip] bump/beta 12.4.2-2-x
skip-checks: true
2023-08-22 17:56:58 +00:00
Jaco cf9082e03a Adjust BE u8aTo{Bn, BigInt, Number} check (#1868)
* Adjust BE u8aTo{Bn, BigInt, Numer} check

* Adjust function names (liberal find-and-replace)
2023-08-22 20:50:50 +03:00
github-actions[bot] 3dce4fe04a [CI Skip] bump/beta 12.4.2-1-x
skip-checks: true
2023-08-22 17:16:39 +00:00
Jaco 55ebc4f0d9 Check sign flag for i{8, 16, 32, ...} conversions (#1867)
* Check sign flag for i{8, 16, 32, ...} conversions

* Ensure negative path is tested on i32 perf

* CHANGELOG

* Comment check on top-most signed bit

* toBn test array

* toNumber uses exposed toBn tests

* Re-use tests in toBn

* Re-use expectations inside bnToU8a

* Remove explicit BE (swap to non-optimal reverse)

* Adjust

* Remove defunct "only BE" comment

* typo

* Use bnToU8a tests in biToU8a

* Flatten tests

* Additional tests

* Additional tests
2023-08-22 20:08:30 +03:00
github-actions[bot] ce2122e9fa [CI Skip] bump/beta 12.4.2-0-x
skip-checks: true
2023-08-20 06:55:29 +00:00
Jaco 0fb55fe633 Bump deps (#1865) 2023-08-20 09:49:19 +03:00
github-actions[bot] adca13bc8c [CI Skip] release/stable 12.4.1
skip-checks: true
2023-08-17 12:30:06 +00:00
Jaco b939c3593c 12.4.1 (#1864) 2023-08-17 15:21:30 +03:00
github-actions[bot] aa70b81a89 [CI Skip] bump/beta 12.3.3-12-x
skip-checks: true
2023-08-17 09:04:14 +00:00
Jaco f3e1d6beda Bump deps (#1863)
* Bump deps

* Adjust Buffer* types
2023-08-17 11:56:46 +03:00
github-actions[bot] 754bc4dc21 [CI Skip] bump/beta 12.3.3-11-x
skip-checks: true
2023-08-16 09:28:29 +00:00
Jaco a8df82dfe0 Update internal buffer types (#1862)
* Update internal buffer types

* u8aToBuffer/isBuffer does not require Buffer type

* Re-add BufferObj equals
2023-08-16 12:22:18 +03:00
github-actions[bot] 4ff56f5cfe [CI Skip] bump/beta 12.3.3-10-x
skip-checks: true
2023-08-16 08:18:29 +00:00
Jaco 1fd9f04458 Bump dev (#1861)
* Bump dev

* Adjust linting
2023-08-16 11:12:06 +03:00
github-actions[bot] a28306f487 [CI Skip] bump/beta 12.3.3-9-x
skip-checks: true
2023-08-16 06:23:08 +00:00
Jaco 19941bcb61 Bump deps (#1860) 2023-08-16 09:16:49 +03:00
github-actions[bot] 2cb85866ab [CI Skip] bump/beta 12.3.3-8-x
skip-checks: true
2023-08-01 13:10:02 +00:00
Jaco 8556de1fa2 Bump dev deps (#1859) 2023-08-01 16:02:08 +03:00
github-actions[bot] 143d070d21 [CI Skip] bump/beta 12.3.3-7-x
skip-checks: true
2023-07-27 11:13:56 +00:00
Jaco 2a53b1121e Bump deps (#1857) 2023-07-27 14:06:32 +03:00
github-actions[bot] 0733137f79 [CI Skip] bump/beta 12.3.3-6-x
skip-checks: true
2023-07-21 06:45:20 +00:00
Jaco cc918660cb Bump deps (#1856) 2023-07-21 09:38:52 +03:00
github-actions[bot] 3527f8c7d9 [CI Skip] bump/beta 12.3.3-5-x
skip-checks: true
2023-07-15 07:04:24 +00:00
Jaco 41caf2fd6d Bump dev (w/ ts-eslint updates) (#1854)
* Bump dev (w/ ts-eslint updates)

* Adjust ipfs compat check
2023-07-15 09:57:35 +03:00
github-actions[bot] d407513dd1 [CI Skip] bump/beta 12.3.3-4-x
skip-checks: true
2023-07-06 07:35:28 +00:00
Jaco bd76349552 Bump deps (#1853)
* Bump deps

* Rebuild networks test
2023-07-06 10:29:31 +03:00
github-actions[bot] 0ec894b732 [CI Skip] bump/beta 12.3.3-3-x
skip-checks: true
2023-06-27 08:42:17 +00:00
Jaco be4cb52dd3 Bump deps (#1851)
* Bump deps

* Update
2023-06-27 11:36:14 +03:00
github-actions[bot] 456eaeeb94 [CI Skip] bump/beta 12.3.3-2-x
skip-checks: true
2023-06-21 06:22:14 +00:00
Jaco 0ec50b6159 Support for signRaw on Ledger SubstrateApp (#1849)
* Support for signRaw on Ledger SubstrateApp

* Adjust with callback return

* Ensure message is wrapped before signing
2023-06-21 09:15:10 +03:00
github-actions[bot] 98336fd2e5 [CI Skip] bump/beta 12.3.3-1-x
skip-checks: true
2023-06-21 05:30:22 +00:00
Jaco 7b3bbd3ef2 Bump deps (#1850) 2023-06-21 08:24:21 +03:00
github-actions[bot] 49afd1fe09 [CI Skip] bump/beta 12.3.3-0-x
skip-checks: true
2023-06-16 06:42:19 +00:00
Jaco 0df17104d5 Use import.meta.url instead of process.cwd() (#1847) 2023-06-16 09:35:40 +03:00
123 changed files with 1777 additions and 2110 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2023 @polkadot/dev authors & contributors
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
module.exports = require('@polkadot/dev/config/prettier.cjs');
+20
View File
@@ -1,5 +1,25 @@
# CHANGELOG
## 12.4.2 Aug 23, 2023
Changes:
- Fix `u8aTo{BigInt, Bn, Number}` for non-negative `i{8, 16, 32...}` inputs
- Extend `u8aToBuffer` with `hasBuffer` check
- Adjust util tests (extract input/output arrays)
## 12.4.1 Aug 17, 2023
Changes:
- Add support for Ledger `signRaw`, as exposed by lower-level
- Update code to use `?.` shortcuts where appropriate
- Adjust `u8aToBuffer` & `isBuffer` typings to not require `Buffer`
- Use `stringify/import.meta.url` helpers in specs
- Upgrade dependencies to latest stable versions
## 12.3.2 Jun 12, 2023
Changes:
+1 -1
View File
@@ -1,4 +1,4 @@
1627 Jaco 12.3.2 (#1846)
1648 Jaco 12.4.2 (#1872)
13 Carlo Sala feat(networks): add zeitgeist Ledger support (#1840)
9 Antoine Estienne Add eth uri keyring test (#1291)
6 Amaury Martiny Add tests from Rust (#283)
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2023 @polkadot/dev authors & contributors
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import baseConfig from '@polkadot/dev/config/eslint';
+6 -6
View File
@@ -14,10 +14,10 @@
},
"sideEffects": false,
"type": "module",
"version": "12.3.2",
"version": "12.4.2",
"versions": {
"git": "12.3.2",
"npm": "12.3.2"
"git": "12.4.2",
"npm": "12.4.2"
},
"workspaces": [
"packages/*"
@@ -37,10 +37,10 @@
"test:one": "polkadot-dev-run-test --env browser"
},
"devDependencies": {
"@polkadot/dev": "^0.75.19",
"@types/node": "^20.3.0"
"@polkadot/dev": "^0.76.18",
"@types/node": "^20.5.3"
},
"resolutions": {
"typescript": "^5.1.3"
"typescript": "^5.1.6"
}
}
+7 -7
View File
@@ -14,18 +14,18 @@
},
"sideEffects": false,
"type": "module",
"version": "12.3.2",
"version": "12.4.2",
"browser": "browser.js",
"main": "node.js",
"react-native": "react-native.js",
"dependencies": {
"@ledgerhq/hw-transport": "^6.28.4",
"@ledgerhq/hw-transport-webhid": "^6.27.15",
"@ledgerhq/hw-transport-webusb": "^6.27.15",
"@polkadot/util": "12.3.2",
"tslib": "^2.5.3"
"@ledgerhq/hw-transport": "^6.28.8",
"@ledgerhq/hw-transport-webhid": "^6.27.19",
"@ledgerhq/hw-transport-webusb": "^6.27.19",
"@polkadot/util": "12.4.2",
"tslib": "^2.6.2"
},
"optionalDependencies": {
"@ledgerhq/hw-transport-node-hid-singleton": "^6.28.12"
"@ledgerhq/hw-transport-node-hid-singleton": "^6.28.18"
}
}
@@ -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: '12.3.2' };
export const packageInfo = { name: '@polkadot/hw-ledger-transports', path: 'auto', type: 'auto', version: '12.4.2' };
+5 -5
View File
@@ -17,12 +17,12 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "12.3.2",
"version": "12.4.2",
"main": "index.js",
"dependencies": {
"@polkadot/hw-ledger-transports": "12.3.2",
"@polkadot/util": "12.3.2",
"@zondax/ledger-substrate": "^0.40.7",
"tslib": "^2.5.3"
"@polkadot/hw-ledger-transports": "12.4.2",
"@polkadot/util": "12.4.2",
"@zondax/ledger-substrate": "^0.41.1",
"tslib": "^2.6.2"
}
}
+20 -9
View File
@@ -8,7 +8,7 @@ import type { AccountOptions, LedgerAddress, LedgerSignature, LedgerVersion } fr
import { newSubstrateApp } from '@zondax/ledger-substrate';
import { transports } from '@polkadot/hw-ledger-transports';
import { hexAddPrefix, u8aToBuffer } from '@polkadot/util';
import { hexAddPrefix, u8aToBuffer, u8aWrapBytes } from '@polkadot/util';
import { LEDGER_DEFAULT_ACCOUNT, LEDGER_DEFAULT_CHANGE, LEDGER_DEFAULT_INDEX, LEDGER_SUCCESS_CODE } from './constants.js';
import { ledgerApps } from './defaults.js';
@@ -30,6 +30,17 @@ async function wrapError <T extends WrappedResult> (promise: Promise<T>): Promis
return result;
}
/** @internal Wraps a sign/signRaw call and returns the associated signature */
function sign (method: 'sign' | 'signRaw', message: Uint8Array, accountOffset = 0, addressOffset = 0, { account = LEDGER_DEFAULT_ACCOUNT, addressIndex = LEDGER_DEFAULT_INDEX, change = LEDGER_DEFAULT_CHANGE }: Partial<AccountOptions> = {}): (app: SubstrateApp) => Promise<LedgerSignature> {
return async (app: SubstrateApp): Promise<LedgerSignature> => {
const { signature } = await wrapError(app[method](account + accountOffset, change, addressIndex + addressOffset, u8aToBuffer(message)));
return {
signature: hexAddPrefix(signature.toString('hex'))
};
};
}
/**
* @name Ledger
*
@@ -91,15 +102,15 @@ export class Ledger {
/**
* Signs a transaction on the Ledger device
*/
public async sign (message: Uint8Array, accountOffset = 0, addressOffset = 0, { account = LEDGER_DEFAULT_ACCOUNT, addressIndex = LEDGER_DEFAULT_INDEX, change = LEDGER_DEFAULT_CHANGE }: Partial<AccountOptions> = {}): Promise<LedgerSignature> {
return this.withApp(async (app: SubstrateApp): Promise<LedgerSignature> => {
const buffer = u8aToBuffer(message);
const { signature } = await wrapError(app.sign(account + accountOffset, change, addressIndex + addressOffset, buffer));
public async sign (message: Uint8Array, accountOffset?: number, addressOffset?: number, options?: Partial<AccountOptions>): Promise<LedgerSignature> {
return this.withApp(sign('sign', message, accountOffset, addressOffset, options));
}
return {
signature: hexAddPrefix(signature.toString('hex'))
};
});
/**
* Signs a message (non-transactional) on the Ledger device
*/
public async signRaw (message: Uint8Array, accountOffset?: number, addressOffset?: number, options?: Partial<AccountOptions>): Promise<LedgerSignature> {
return this.withApp(sign('signRaw', u8aWrapBytes(message), accountOffset, addressOffset, options));
}
/**
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/hw-ledger', path: 'auto', type: 'auto', version: '12.3.2' };
export const packageInfo = { name: '@polkadot/hw-ledger', path: 'auto', type: 'auto', version: '12.4.2' };
+6 -6
View File
@@ -18,15 +18,15 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "12.3.2",
"version": "12.4.2",
"main": "index.js",
"dependencies": {
"@polkadot/util": "12.3.2",
"@polkadot/util-crypto": "12.3.2",
"tslib": "^2.5.3"
"@polkadot/util": "12.4.2",
"@polkadot/util-crypto": "12.4.2",
"tslib": "^2.6.2"
},
"peerDependencies": {
"@polkadot/util": "12.3.2",
"@polkadot/util-crypto": "12.3.2"
"@polkadot/util": "12.4.2",
"@polkadot/util-crypto": "12.4.2"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/keyring', path: 'auto', type: 'auto', version: '12.3.2' };
export const packageInfo = { name: '@polkadot/keyring', path: 'auto', type: 'auto', version: '12.4.2' };
+4 -5
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { EncryptedJsonEncoding, Keypair, KeypairType } from '@polkadot/util-crypto/types';
import type { KeyringPair, KeyringPair$Json, KeyringPair$Meta, SignOptions } from '../types.js';
import type { PairInfo } from './types.js';
@@ -165,7 +164,7 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
setMeta: (additional: KeyringPair$Meta): void => {
meta = objectSpread({}, meta, additional);
},
sign: (message: HexString | string | Uint8Array, options: SignOptions = {}): Uint8Array => {
sign: (message: string | Uint8Array, options: SignOptions = {}): Uint8Array => {
if (isLocked(secretKey)) {
throw new Error('Cannot sign with a locked key pair');
}
@@ -192,10 +191,10 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
unlock: (passphrase?: string): void => {
return decodePkcs8(passphrase);
},
verify: (message: HexString | string | Uint8Array, signature: HexString | string | Uint8Array, signerPublic: HexString | string | Uint8Array): boolean => {
verify: (message: string | Uint8Array, signature: string | Uint8Array, signerPublic: string | Uint8Array): boolean => {
return signatureVerify(message, signature, TYPE_ADDRESS[type](u8aToU8a(signerPublic))).isValid;
},
vrfSign: (message: HexString | string | Uint8Array, context?: HexString | string | Uint8Array, extra?: string | Uint8Array): Uint8Array => {
vrfSign: (message: string | Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): Uint8Array => {
if (isLocked(secretKey)) {
throw new Error('Cannot sign with a locked key pair');
}
@@ -208,7 +207,7 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
return u8aConcat(vrfHash(proof, context, extra), proof);
},
vrfVerify: (message: HexString | string | Uint8Array, vrfResult: Uint8Array, signerPublic: HexString | Uint8Array | string, context?: HexString | string | Uint8Array, extra?: HexString | string | Uint8Array): boolean => {
vrfVerify: (message: string | Uint8Array, vrfResult: Uint8Array, signerPublic: Uint8Array | string, context?: string | Uint8Array, extra?: string | Uint8Array): boolean => {
if (type === 'sr25519') {
return sr25519VrfVerify(message, vrfResult, publicKey, context, extra);
}
+2 -3
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { KeyringPair, KeyringPairs } from './types.js';
import { isHex, isU8a, u8aToHex, u8aToU8a } from '@polkadot/util';
@@ -22,7 +21,7 @@ export class Pairs implements KeyringPairs {
return Object.values(this.#map);
}
public get (address: HexString | string | Uint8Array): KeyringPair {
public get (address: string | Uint8Array): KeyringPair {
const pair = this.#map[decodeAddress(address).toString()];
if (!pair) {
@@ -36,7 +35,7 @@ export class Pairs implements KeyringPairs {
return pair;
}
public remove (address: HexString | string | Uint8Array): void {
public remove (address: string | Uint8Array): void {
delete this.#map[decodeAddress(address).toString()];
}
}
+1 -1
View File
@@ -119,7 +119,7 @@ function createMeta (name?: string, seed?: string) {
return {
isTesting: true,
name: name || (seed && seed.replace('//', '_').toLowerCase())
name: name || seed?.replace('//', '_').toLowerCase()
};
}
+1 -3
View File
@@ -42,9 +42,7 @@ describe('testingPairs', (): void => {
const keyring = new Keyring({ type: 'ethereum' });
const pair = keyring.createFromUri('0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133');
expect(
pair && pair.address
).toEqual(TEST_ADD);
expect(pair?.address).toEqual(TEST_ADD);
});
describe('checks eth test addresses', (): void => {
+3 -1
View File
@@ -47,7 +47,9 @@ export function createTestPairs <O extends KeyringOptions, M = DetectMap<O>> (op
const map: TestKeyringMap = { nobody: nobody() };
for (const p of pairs) {
map[p.meta.name as string] = p;
if (p.meta.name) {
map[p.meta.name] = p;
}
}
return map as M;
+5 -5
View File
@@ -70,7 +70,7 @@ export interface KeyringPair$Meta extends KeyringPair$MetaExtension, KeyringPair
export interface KeyringPair$Json extends EncryptedJson {
/** The ss58 encoded address or the hex-encoded version (the latter is for ETH-compat chains) */
address: string | HexString;
address: string;
/** The underlying metadata associated with the keypair */
meta: KeyringPair$Meta;
}
@@ -95,12 +95,12 @@ export interface KeyringPair {
encodePkcs8 (passphrase?: string): Uint8Array;
lock (): void;
setMeta (meta: KeyringPair$Meta): void;
sign (message: HexString | string | Uint8Array, options?: SignOptions): Uint8Array;
sign (message: string | Uint8Array, options?: SignOptions): Uint8Array;
toJson (passphrase?: string): KeyringPair$Json;
unlock (passphrase?: string): void;
verify (message: HexString | string | Uint8Array, signature: Uint8Array, signerPublic: HexString | string | Uint8Array): boolean;
vrfSign (message: HexString | string | Uint8Array, context?: HexString | string | Uint8Array, extra?: HexString | string | Uint8Array): Uint8Array;
vrfVerify (message: HexString | string | Uint8Array, vrfResult: Uint8Array, signerPublic: HexString | Uint8Array | string, context?: HexString | string | Uint8Array, extra?: HexString | string | Uint8Array): boolean;
verify (message: string | Uint8Array, signature: Uint8Array, signerPublic: string | Uint8Array): boolean;
vrfSign (message: string | Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): Uint8Array;
vrfVerify (message: string | Uint8Array, vrfResult: Uint8Array, signerPublic: string | Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): boolean;
}
export interface KeyringPairs {
+5 -5
View File
@@ -15,14 +15,14 @@
},
"sideEffects": false,
"type": "module",
"version": "12.3.2",
"version": "12.4.2",
"main": "index.js",
"dependencies": {
"@polkadot/util": "12.3.2",
"@substrate/ss58-registry": "^1.40.0",
"tslib": "^2.5.3"
"@polkadot/util": "12.4.2",
"@substrate/ss58-registry": "^1.43.0",
"tslib": "^2.6.2"
},
"devDependencies": {
"@polkadot/hw-ledger": "12.3.2"
"@polkadot/hw-ledger": "12.4.2"
}
}
+2 -2
View File
@@ -29,8 +29,8 @@ function toExpanded (o: KnownSubstrate): SubstrateNetwork {
n.isIgnored = n.isTestnet || (
!(
o.standardAccount &&
o.decimals && o.decimals.length &&
o.symbols && o.symbols.length
o.decimals?.length &&
o.symbols?.length
) &&
o.prefix !== 42
);
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/networks', path: 'auto', type: 'auto', version: '12.3.2' };
export const packageInfo = { name: '@polkadot/networks', path: 'auto', type: 'auto', version: '12.4.2' };
+11 -5
View File
@@ -5,16 +5,22 @@
import known from '@substrate/ss58-registry';
import fs from 'node:fs';
import path from 'node:path';
const other = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'packages/networks/test/ss58registry.json'), 'utf-8')) as unknown;
import { stringify } from '@polkadot/util';
describe('@substrate/ss58-registry', (): void => {
it('has known values', (): void => {
const json = JSON.stringify(known, null, 2);
const testUrl = new URL('../test/ss58registry.json', import.meta.url);
const json = stringify(known, 2);
try {
expect(JSON.parse(json)).toEqual(other);
expect(
JSON.parse(json)
).toEqual(
JSON.parse(
fs.readFileSync(testUrl, 'utf-8')
)
);
} catch (error) {
if (process.env['GITHUB_REPOSITORY']) {
console.error(json);
@@ -22,7 +28,7 @@ describe('@substrate/ss58-registry', (): void => {
throw error;
}
fs.writeFileSync(path.join(process.cwd(), 'packages/networks/test/ss58registry.json'), json, { flag: 'w' });
fs.writeFileSync(testUrl, json, { flag: 'w' });
}
});
});
+134 -6
View File
@@ -222,15 +222,13 @@
"network": "darwinia",
"displayName": "Darwinia Network",
"symbols": [
"RING",
"KTON"
"RING"
],
"decimals": [
9,
9
18
],
"standardAccount": "*25519",
"website": "https://darwinia.network/"
"standardAccount": "secp256k1",
"website": "https://darwinia.network"
},
{
"prefix": 19,
@@ -258,6 +256,19 @@
"standardAccount": "*25519",
"website": "https://stafi.io"
},
{
"prefix": 21,
"network": "karmachain",
"displayName": "Karmacoin",
"symbols": [
"KCOIN"
],
"decimals": [
6
],
"standardAccount": "*25519",
"website": "https://karmaco.in"
},
{
"prefix": 22,
"network": "dock-pos-mainnet",
@@ -713,6 +724,19 @@
"standardAccount": "*25519",
"website": "https://hydradx.io"
},
{
"prefix": 64,
"network": "ewx",
"displayName": "Energy Web X",
"symbols": [
"EWT"
],
"decimals": [
18
],
"standardAccount": "*25519",
"website": "https://www.energyweb.org"
},
{
"prefix": 65,
"network": "aventus",
@@ -1168,6 +1192,32 @@
"standardAccount": "*25519",
"website": "https://sora.org"
},
{
"prefix": 440,
"network": "allfeat_network",
"displayName": "Allfeat Network",
"symbols": [
"AFT"
],
"decimals": [
12
],
"standardAccount": "*25519",
"website": "https://allfeat.network"
},
{
"prefix": 666,
"network": "metaquity_network",
"displayName": "Metaquity Network",
"symbols": [
"MQTY"
],
"decimals": [
18
],
"standardAccount": "*25519",
"website": "https://metaquity.xyz/"
},
{
"prefix": 789,
"network": "geek",
@@ -1402,6 +1452,19 @@
"standardAccount": "*25519",
"website": "https://chainflip.io/"
},
{
"prefix": 2199,
"network": "moonsama",
"displayName": "Moonsama",
"symbols": [
"SAMA"
],
"decimals": [
18
],
"standardAccount": "secp256k1",
"website": "https://moonsama.com"
},
{
"prefix": 2206,
"network": "ICE",
@@ -1441,6 +1504,19 @@
"standardAccount": "*25519",
"website": "https://subspace.network"
},
{
"prefix": 3333,
"network": "peerplays",
"displayName": "Peerplays",
"symbols": [
"PPY"
],
"decimals": [
18
],
"standardAccount": "secp256k1",
"website": "https://www.peerplays.com/"
},
{
"prefix": 4006,
"network": "tangle",
@@ -1523,6 +1599,19 @@
"standardAccount": "*25519",
"website": "https://gmordie.com"
},
{
"prefix": 7306,
"network": "krigan",
"displayName": "Krigan Network",
"symbols": [
"KRGN"
],
"decimals": [
9
],
"standardAccount": "*25519",
"website": "https://krigan.network"
},
{
"prefix": 7391,
"network": "unique_mainnet",
@@ -1536,6 +1625,19 @@
"standardAccount": "*25519",
"website": "https://unique.network"
},
{
"prefix": 8866,
"network": "golden_gate",
"displayName": "Golden Gate",
"symbols": [
"GGX"
],
"decimals": [
18
],
"standardAccount": "*25519",
"website": "https://ggxchain.io/"
},
{
"prefix": 8883,
"network": "sapphire_mainnet",
@@ -1549,6 +1651,19 @@
"standardAccount": "*25519",
"website": "https://unique.network"
},
{
"prefix": 8886,
"network": "golden_gate_sydney",
"displayName": "Golden Gate Sydney",
"symbols": [
"GGXT"
],
"decimals": [
18
],
"standardAccount": "*25519",
"website": "https://ggxchain.io/"
},
{
"prefix": 9072,
"network": "hashed",
@@ -1691,5 +1806,18 @@
],
"standardAccount": "*25519",
"website": "https://bittensor.com"
},
{
"prefix": 14697,
"network": "goro",
"displayName": "GORO Network",
"symbols": [
"GORO"
],
"decimals": [
9
],
"standardAccount": "*25519",
"website": "https://goro.network"
}
]
+9 -9
View File
@@ -20,7 +20,7 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "12.3.2",
"version": "12.4.2",
"browser": {
"crypto": false,
"stream": false
@@ -29,16 +29,16 @@
"dependencies": {
"@noble/curves": "1.1.0",
"@noble/hashes": "1.3.1",
"@polkadot/networks": "12.3.2",
"@polkadot/util": "12.3.2",
"@polkadot/wasm-crypto": "^7.2.1",
"@polkadot/wasm-util": "^7.2.1",
"@polkadot/x-bigint": "12.3.2",
"@polkadot/x-randomvalues": "12.3.2",
"@polkadot/networks": "12.4.2",
"@polkadot/util": "12.4.2",
"@polkadot/wasm-crypto": "^7.2.2",
"@polkadot/wasm-util": "^7.2.2",
"@polkadot/x-bigint": "12.4.2",
"@polkadot/x-randomvalues": "12.4.2",
"@scure/base": "1.1.1",
"tslib": "^2.5.3"
"tslib": "^2.6.2"
},
"peerDependencies": {
"@polkadot/util": "12.3.2"
"@polkadot/util": "12.4.2"
}
}
@@ -1,14 +1,12 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { decodeAddress } from './decode.js';
/**
* @name addressToEvm
* @summary Converts an SS58 address to its corresponding EVM address.
*/
export function addressToEvm (address: HexString | string | Uint8Array, ignoreChecksum?: boolean): Uint8Array {
export function addressToEvm (address: string | Uint8Array, ignoreChecksum?: boolean): Uint8Array {
return decodeAddress(address, ignoreChecksum).subarray(0, 20);
}
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js';
import { base58Decode } from '../base58/index.js';
@@ -14,7 +13,7 @@ import { defaults } from './defaults.js';
* @description
* From the provided input, validate that the address is a valid input.
*/
export function checkAddress (address: HexString | string, prefix: Prefix): [boolean, string | null] {
export function checkAddress (address: string, prefix: Prefix): [boolean, string | null] {
let decoded;
try {
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js';
// Original implementation: https://github.com/paritytech/polka-ui/blob/4858c094684769080f5811f32b081dd7780b0880/src/polkadot.js#L6
@@ -11,7 +10,7 @@ import { base58Decode } from '../base58/index.js';
import { checkAddressChecksum } from './checksum.js';
import { defaults } from './defaults.js';
export function decodeAddress (encoded?: HexString | string | Uint8Array | null, ignoreChecksum?: boolean, ss58Format: Prefix = -1): Uint8Array {
export function decodeAddress (encoded?: string | Uint8Array | null, ignoreChecksum?: boolean, ss58Format: Prefix = -1): Uint8Array {
if (!encoded) {
throw new Error('Invalid empty address passed');
}
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { DeriveJunction } from '../key/DeriveJunction.js';
import type { Prefix } from './types.js';
@@ -20,7 +19,7 @@ function filterHard ({ isHard }: DeriveJunction): boolean {
* @description
* Creates a sr25519 derived address based on the input address/publicKey and the uri supplied.
*/
export function deriveAddress (who: HexString | Uint8Array | string, suri: string, ss58Format?: Prefix): string {
export function deriveAddress (who: string | Uint8Array, suri: string, ss58Format?: Prefix): string {
const { path } = keyExtractPath(suri);
if (!path.length || path.every(filterHard)) {
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js';
// Original implementation: https://github.com/paritytech/polka-ui/blob/4858c094684769080f5811f32b081dd7780b0880/src/polkadot.js#L34
@@ -12,7 +11,7 @@ import { decodeAddress } from './decode.js';
import { defaults } from './defaults.js';
import { sshash } from './sshash.js';
export function encodeAddress (key: HexString | Uint8Array | string, ss58Format: Prefix = defaults.prefix): string {
export function encodeAddress (key: string | Uint8Array, ss58Format: Prefix = defaults.prefix): string {
// decode it, this means we can re-encode an address
const u8a = decodeAddress(key);
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js';
import { decodeAddress } from './decode.js';
@@ -15,6 +14,6 @@ import { createKeyDerived } from './keyDerived.js';
* @description
* Creates a Substrate derived address based on the input address/publicKey and the index supplied.
*/
export function encodeDerivedAddress (who: HexString | Uint8Array | string, index: bigint | BN | number, ss58Format?: Prefix): string {
export function encodeDerivedAddress (who: string | Uint8Array, index: bigint | BN | number, ss58Format?: Prefix): string {
return encodeAddress(createKeyDerived(decodeAddress(who), index), ss58Format);
}
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js';
import { encodeAddress } from './encode.js';
@@ -14,6 +13,6 @@ import { createKeyMulti } from './keyMulti.js';
* @description
* Creates a Substrate multisig address based on the input address and the required threshold.
*/
export function encodeMultiAddress (who: (HexString | Uint8Array | string)[], threshold: bigint | BN | number, ss58Format?: Prefix): string {
export function encodeMultiAddress (who: (string | Uint8Array)[], threshold: bigint | BN | number, ss58Format?: Prefix): string {
return encodeAddress(createKeyMulti(who, threshold), ss58Format);
}
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aEq } from '@polkadot/util';
import { decodeAddress } from './decode.js';
@@ -21,6 +19,6 @@ import { decodeAddress } from './decode.js';
* u8aEq(new Uint8Array([0x68, 0x65]), new Uint8Array([0x68, 0x65])); // true
* ```
*/
export function addressEq (a: HexString | string | Uint8Array, b: HexString | string | Uint8Array): boolean {
export function addressEq (a: string | Uint8Array, b: string | Uint8Array): boolean {
return u8aEq(decodeAddress(a), decodeAddress(b));
}
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { HashType } from '../secp256k1/types.js';
import type { Prefix } from './types.js';
@@ -14,7 +13,7 @@ import { encodeAddress } from './encode.js';
* @name evmToAddress
* @summary Converts an EVM address to its corresponding SS58 address.
*/
export function evmToAddress (evmAddress: HexString | string | Uint8Array, ss58Format?: Prefix, hashType: HashType = 'blake2'): string {
export function evmToAddress (evmAddress: string | Uint8Array, ss58Format?: Prefix, hashType: HashType = 'blake2'): string {
const message = u8aConcat('evm:', evmAddress);
if (message.length !== 24) {
+1 -2
View File
@@ -1,12 +1,11 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js';
import { validateAddress } from './validate.js';
export function isAddress (address?: HexString | string | null, ignoreChecksum?: boolean, ss58Format?: Prefix): address is string {
export function isAddress (address?: string | null, ignoreChecksum?: boolean, ss58Format?: Prefix): address is string {
try {
return validateAddress(address, ignoreChecksum, ss58Format);
} catch {
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import { bnToU8a, stringToU8a, u8aConcat } from '@polkadot/util';
@@ -12,7 +11,7 @@ import { decodeAddress } from './decode.js';
const PREFIX = stringToU8a('modlpy/utilisuba');
export function createKeyDerived (who: HexString | Uint8Array | string, index: bigint | BN | number): Uint8Array {
export function createKeyDerived (who: string | Uint8Array, index: bigint | BN | number): Uint8Array {
return blake2AsU8a(
u8aConcat(
PREFIX,
+1 -2
View File
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import { bnToU8a, compactToU8a, stringToU8a, u8aConcat, u8aSorted } from '@polkadot/util';
@@ -12,7 +11,7 @@ import { addressToU8a } from './util.js';
const PREFIX = stringToU8a('modlpy/utilisuba');
export function createKeyMulti (who: (HexString | Uint8Array | string)[], threshold: bigint | BN | number): Uint8Array {
export function createKeyMulti (who: (string | Uint8Array)[], threshold: bigint | BN | number): Uint8Array {
return blake2AsU8a(
u8aConcat(
PREFIX,
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js';
import { u8aSorted } from '@polkadot/util';
@@ -9,7 +8,7 @@ import { u8aSorted } from '@polkadot/util';
import { encodeAddress } from './encode.js';
import { addressToU8a } from './util.js';
export function sortAddresses (addresses: (HexString | Uint8Array | string)[], ss58Format?: Prefix): string[] {
export function sortAddresses (addresses: (string | Uint8Array)[], ss58Format?: Prefix): string[] {
const u8aToAddress = (u8a: Uint8Array) => encodeAddress(u8a, ss58Format);
return u8aSorted(
+1 -2
View File
@@ -1,11 +1,10 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js';
import { decodeAddress } from './decode.js';
export function validateAddress (encoded?: HexString | string | null, ignoreChecksum?: boolean, ss58Format?: Prefix): encoded is string {
export function validateAddress (encoded?: string | null, ignoreChecksum?: boolean, ss58Format?: Prefix): encoded is string {
return !!decodeAddress(encoded, ignoreChecksum, ss58Format);
}
+1 -1
View File
@@ -68,7 +68,7 @@ export function createValidate ({ chars, ipfs, type, withPadding }: Config): Val
return (value?: unknown, ipfsCompat?: boolean): value is string => {
if (typeof value !== 'string') {
throw new Error(`Expected ${type} string input`);
} else if (ipfs && ipfsCompat && value[0] !== ipfs) {
} else if (ipfs && ipfsCompat && !value.startsWith(ipfs)) {
throw new Error(`Expected ipfs-compatible ${type} to start with '${ipfs}'`);
}
+1 -1
View File
@@ -6,7 +6,7 @@
* @description Trims padding characters
*/
export function base64Trim (value: string): string {
while (value.length && value[value.length - 1] === '=') {
while (value.length && value.endsWith('=')) {
value = value.slice(0, -1);
}
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { blake2b as blake2bJs } from '@noble/hashes/blake2b';
import { hasBigInt, u8aToU8a } from '@polkadot/util';
@@ -24,7 +22,7 @@ import { createAsHex } from '../helpers.js';
* blake2AsU8a('abc'); // => [0xba, 0x80, 0xa5, 0x3f, 0x98, 0x1c, 0x4d, 0x0d]
* ```
*/
export function blake2AsU8a (data: HexString | Uint8Array | string, bitLength: 64 | 128 | 256 | 384 | 512 = 256, key?: Uint8Array | null, onlyJs?: boolean): Uint8Array {
export function blake2AsU8a (data: string | Uint8Array, bitLength: 64 | 128 | 256 | 384 | 512 = 256, key?: Uint8Array | null, onlyJs?: boolean): Uint8Array {
const byteLength = Math.ceil(bitLength / 8);
const u8a = u8aToU8a(data);
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../types.js';
import { ed25519 } from '@noble/curves/ed25519';
@@ -23,7 +22,7 @@ import { ed25519Sign as wasmSign, isReady } from '@polkadot/wasm-crypto';
* ed25519Sign([...], [...]); // => [...]
* ```
*/
export function ed25519Sign (message: HexString | Uint8Array | string, { publicKey, secretKey }: Partial<Keypair>, onlyJs?: boolean): Uint8Array {
export function ed25519Sign (message: string | Uint8Array, { publicKey, secretKey }: Partial<Keypair>, onlyJs?: boolean): Uint8Array {
if (!secretKey) {
throw new Error('Expected a valid secretKey');
} else if (!publicKey) {
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { ed25519 } from '@noble/curves/ed25519';
import { hasBigInt, u8aToU8a } from '@polkadot/util';
@@ -22,7 +20,7 @@ import { ed25519Verify as wasmVerify, isReady } from '@polkadot/wasm-crypto';
* ed25519Verify([...], [...], [...]); // => true/false
* ```
*/
export function ed25519Verify (message: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, publicKey: HexString | Uint8Array | string, onlyJs?: boolean): boolean {
export function ed25519Verify (message: string | Uint8Array, signature: string | Uint8Array, publicKey: string | Uint8Array, onlyJs?: boolean): boolean {
const messageU8a = u8aToU8a(message);
const publicKeyU8a = u8aToU8a(publicKey);
const signatureU8a = u8aToU8a(signature);
+1 -1
View File
@@ -16,7 +16,7 @@ function getH160 (u8a: Uint8Array): Uint8Array {
return u8a.slice(-20);
}
export function ethereumEncode (addressOrPublic?: HexString | string | Uint8Array): HexString {
export function ethereumEncode (addressOrPublic?: string | Uint8Array): HexString {
if (!addressOrPublic) {
return '0x';
}
@@ -1,13 +1,11 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { isHex } from '@polkadot/util';
import { isEthereumChecksum } from './isChecksum.js';
export function isEthereumAddress (address?: HexString | string): boolean {
export function isEthereumAddress (address?: string): boolean {
if (!address || address.length !== 42 || !isHex(address)) {
return false;
} else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) {
+4 -4
View File
@@ -21,14 +21,14 @@ export function createAsHex <T extends (...args: never[]) => Uint8Array> (fn: T)
}
/** @internal */
export function createBitHasher (bitLength: 256 | 512, fn: (data: HexString | Uint8Array | string, bitLength: 256 | 512, onlyJs?: boolean) => Uint8Array): (data: HexString | Uint8Array | string, onlyJs?: boolean) => Uint8Array {
return (data: HexString | Uint8Array | string, onlyJs?: boolean): Uint8Array =>
export function createBitHasher (bitLength: 256 | 512, fn: (data: string | Uint8Array, bitLength: 256 | 512, onlyJs?: boolean) => Uint8Array): (data: string | Uint8Array, onlyJs?: boolean) => Uint8Array {
return (data: string | Uint8Array, onlyJs?: boolean): Uint8Array =>
fn(data, bitLength, onlyJs);
}
/** @internal */
export function createDualHasher (wa: DualHash, js: DualHash): (value: HexString | Uint8Array | string, bitLength?: 256 | 512, onlyJs?: boolean) => Uint8Array {
return (value: HexString | Uint8Array | string, bitLength: 256 | 512 = 256, onlyJs?: boolean): Uint8Array => {
export function createDualHasher (wa: DualHash, js: DualHash): (value: string | Uint8Array, bitLength?: 256 | 512, onlyJs?: boolean) => Uint8Array {
return (value: string | Uint8Array, bitLength: 256 | 512 = 256, onlyJs?: boolean): Uint8Array => {
const u8a = u8aToU8a(value);
return !hasBigInt || (!onlyJs && isReady())
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
export type EncryptedJsonVersion = '0' | '1' | '2' | '3';
export type EncryptedJsonEncoding = 'none' | 'scrypt' | 'xsalsa20-poly1305';
@@ -14,6 +12,6 @@ export interface EncryptedJsonDescriptor {
}
export interface EncryptedJson {
encoded: HexString | string;
encoded: string;
encoding: EncryptedJsonDescriptor;
}
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { BN, bnToU8a, compactAddLength, hexToU8a, isBigInt, isBn, isHex, isNumber, isString, stringToU8a } from '@polkadot/util';
import { blake2AsU8a } from '../blake2/asU8a.js';
@@ -46,7 +44,7 @@ export class DeriveJunction {
return !this.#isHard;
}
public hard (value: HexString | number | string | bigint | BN | Uint8Array): DeriveJunction {
public hard (value: number | string | bigint | BN | Uint8Array): DeriveJunction {
return this.soft(value).harden();
}
@@ -56,7 +54,7 @@ export class DeriveJunction {
return this;
}
public soft (value: HexString | number | string | bigint | BN | Uint8Array): DeriveJunction {
public soft (value: number | string | bigint | BN | Uint8Array): DeriveJunction {
if (isNumber(value) || isBn(value) || isBigInt(value)) {
return this.soft(bnToU8a(value, BN_LE_256_OPTS));
} else if (isHex(value)) {
+2 -2
View File
@@ -81,7 +81,7 @@ export function mnemonicToEntropy (mnemonic: string, wordlist: string[] = DEFAUL
// calculate the checksum and compare
const matched = entropyBits.match(/(.{1,8})/g);
const entropyBytes = matched && matched.map(binaryToByte);
const entropyBytes = matched?.map(binaryToByte);
if (!entropyBytes || (entropyBytes.length % 4 !== 0) || (entropyBytes.length < 16) || (entropyBytes.length > 32)) {
throw new Error(INVALID_ENTROPY);
@@ -103,7 +103,7 @@ export function entropyToMnemonic (entropy: Uint8Array, wordlist: string[] = DEF
}
const matched = `${bytesToBinary(Array.from(entropy))}${deriveChecksumBits(entropy)}`.match(/(.{1,11})/g);
const mapped = matched && matched.map((b) => wordlist[binaryToByte(b)]);
const mapped = matched?.map((b) => wordlist[binaryToByte(b)]);
if (!mapped || (mapped.length < 12)) {
throw new Error('Unable to map entropy to mnemonic');
@@ -136,7 +136,7 @@ describe('tweetnacl/secretbox', (): void => {
});
describe('tweetnacl/test/04-secretbox.js', (): void => {
for (let i = 0; i < TEST_DATA.length; i++) {
for (let i = 0, count = TEST_DATA.length; i < count; i++) {
const [keyBase64, nonceBase64, msgBase64, expBase64] = TEST_DATA[i];
it(`is ok on "${msgBase64}"`, (): void => {
+1 -1
View File
@@ -958,7 +958,7 @@ function checkLengths (k: Uint8Array, n: Uint8Array): void {
// }
function checkArrayTypes (...args: unknown[]): void {
for (let i = 0; i < args.length; i++) {
for (let i = 0, count = args.length; i < count; i++) {
if (!(args[i] instanceof Uint8Array))
throw new TypeError('unexpected type, use Uint8Array');
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/util-crypto', path: 'auto', type: 'auto', version: '12.3.2' };
export const packageInfo = { name: '@polkadot/util-crypto', path: 'auto', type: 'auto', version: '12.4.2' };
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { pbkdf2 as pbkdf2Js } from '@noble/hashes/pbkdf2';
import { sha512 } from '@noble/hashes/sha512';
@@ -17,7 +15,7 @@ interface Result {
salt: Uint8Array;
}
export function pbkdf2Encode (passphrase?: HexString | Uint8Array | string, salt: Uint8Array = randomAsU8a(), rounds = 2048, onlyJs?: boolean): Result {
export function pbkdf2Encode (passphrase?: string | Uint8Array, salt: Uint8Array = randomAsU8a(), rounds = 2048, onlyJs?: boolean): Result {
const u8aPass = u8aToU8a(passphrase);
const u8aSalt = u8aToU8a(salt);
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Params } from './types.js';
import { scrypt as scryptJs } from '@noble/hashes/scrypt';
@@ -18,7 +17,7 @@ interface Result {
salt: Uint8Array;
}
export function scryptEncode (passphrase?: HexString | Uint8Array | string, salt = randomAsU8a(), params = DEFAULT_PARAMS, onlyJs?: boolean): Result {
export function scryptEncode (passphrase?: string | Uint8Array, salt = randomAsU8a(), params = DEFAULT_PARAMS, onlyJs?: boolean): Result {
const u8a = u8aToU8a(passphrase);
return {
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { HashType } from './types.js';
import { secp256k1 } from '@noble/curves/secp256k1';
@@ -16,7 +15,7 @@ import { secp256k1Expand } from './expand.js';
* @name secp256k1Recover
* @description Recovers a publicKey from the supplied signature
*/
export function secp256k1Recover (msgHash: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, recovery: number, hashType: HashType = 'blake2', onlyJs?: boolean): Uint8Array {
export function secp256k1Recover (msgHash: string | Uint8Array, signature: string | Uint8Array, recovery: number, hashType: HashType = 'blake2', onlyJs?: boolean): Uint8Array {
const sig = u8aToU8a(signature).subarray(0, 64);
const msg = u8aToU8a(msgHash);
const publicKey = !hasBigInt || (!onlyJs && isReady())
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { HashType } from './types.js';
import { u8aEq, u8aToU8a } from '@polkadot/util';
@@ -13,7 +12,7 @@ import { secp256k1Recover } from './recover.js';
* @name secp256k1Verify
* @description Verifies the signature of `message`, using the supplied pair
*/
export function secp256k1Verify (msgHash: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, address: HexString | Uint8Array | string, hashType: HashType = 'blake2', onlyJs?: boolean): boolean {
export function secp256k1Verify (msgHash: string | Uint8Array, signature: string | Uint8Array, address: string | Uint8Array, hashType: HashType = 'blake2', onlyJs?: boolean): boolean {
const sig = u8aToU8a(signature);
if (sig.length !== 65) {
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { KeypairType, VerifyResult } from '../types.js';
import { u8aIsWrapped, u8aToU8a, u8aUnwrapBytes, u8aWrapBytes } from '@polkadot/util';
@@ -87,7 +86,7 @@ function getVerifyFn (signature: Uint8Array): VerifyFn {
: verifyDetect;
}
export function signatureVerify (message: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, addressOrPublicKey: HexString | Uint8Array | string): VerifyResult {
export function signatureVerify (message: string | Uint8Array, signature: string | Uint8Array, addressOrPublicKey: string | Uint8Array): VerifyResult {
const signatureU8a = u8aToU8a(signature);
if (![64, 65, 66].includes(signatureU8a.length)) {
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aToU8a } from '@polkadot/util';
import { sr25519Agree } from '@polkadot/wasm-crypto';
@@ -10,7 +8,7 @@ import { sr25519Agree } from '@polkadot/wasm-crypto';
* @name sr25519Agreement
* @description Key agreement between other's public key and self secret key
*/
export function sr25519Agreement (secretKey: HexString | Uint8Array | string, publicKey: HexString | Uint8Array | string): Uint8Array {
export function sr25519Agreement (secretKey: string | Uint8Array, publicKey: string | Uint8Array): Uint8Array {
const secretKeyU8a = u8aToU8a(secretKey);
const publicKeyU8a = u8aToU8a(publicKey);
@@ -1,12 +1,10 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { isU8a, u8aToU8a } from '@polkadot/util';
import { sr25519DerivePublicSoft } from '@polkadot/wasm-crypto';
export function sr25519DerivePublic (publicKey: HexString | Uint8Array | string, chainCode: Uint8Array): Uint8Array {
export function sr25519DerivePublic (publicKey: string | Uint8Array, chainCode: Uint8Array): Uint8Array {
const publicKeyU8a = u8aToU8a(publicKey);
if (!isU8a(chainCode) || chainCode.length !== 32) {
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../../types.js';
import { u8aToU8a } from '@polkadot/util';
@@ -13,7 +12,7 @@ import { sr25519PairFromU8a } from './fromU8a.js';
* @name sr25519PairFromSeed
* @description Returns a object containing a `publicKey` & `secretKey` generated from the supplied seed.
*/
export function sr25519PairFromSeed (seed: HexString | Uint8Array | string): Keypair {
export function sr25519PairFromSeed (seed: string | Uint8Array): Keypair {
const seedU8a = u8aToU8a(seed);
if (seedU8a.length !== 32) {
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../../types.js';
import { u8aToU8a } from '@polkadot/util';
@@ -10,7 +9,7 @@ const SEC_LEN = 64;
const PUB_LEN = 32;
const TOT_LEN = SEC_LEN + PUB_LEN;
export function sr25519PairFromU8a (full: HexString | Uint8Array | string): Keypair {
export function sr25519PairFromU8a (full: string | Uint8Array): Keypair {
const fullU8a = u8aToU8a(full);
if (fullU8a.length !== TOT_LEN) {
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../types.js';
import { u8aToU8a } from '@polkadot/util';
@@ -11,7 +10,7 @@ import { sr25519Sign as wasmSign } from '@polkadot/wasm-crypto';
* @name sr25519Sign
* @description Returns message signature of `message`, using the supplied pair
*/
export function sr25519Sign (message: HexString | Uint8Array | string, { publicKey, secretKey }: Partial<Keypair>): Uint8Array {
export function sr25519Sign (message: string | Uint8Array, { publicKey, secretKey }: Partial<Keypair>): Uint8Array {
if (publicKey?.length !== 32) {
throw new Error('Expected a valid publicKey, 32-bytes');
} else if (secretKey?.length !== 64) {
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aToU8a } from '@polkadot/util';
import { sr25519Verify as wasmVerify } from '@polkadot/wasm-crypto';
@@ -10,7 +8,7 @@ import { sr25519Verify as wasmVerify } from '@polkadot/wasm-crypto';
* @name sr25519Verify
* @description Verifies the signature of `message`, using the supplied pair
*/
export function sr25519Verify (message: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, publicKey: HexString | Uint8Array | string): boolean {
export function sr25519Verify (message: string | Uint8Array, signature: string | Uint8Array, publicKey: string | Uint8Array): boolean {
const publicKeyU8a = u8aToU8a(publicKey);
const signatureU8a = u8aToU8a(signature);
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../types.js';
import { u8aToU8a } from '@polkadot/util';
@@ -13,7 +12,7 @@ const EMPTY_U8A = new Uint8Array();
* @name sr25519VrfSign
* @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 {
export function sr25519VrfSign (message: string | Uint8Array, { secretKey }: Partial<Keypair>, context: string | Uint8Array = EMPTY_U8A, extra: string | Uint8Array = EMPTY_U8A): Uint8Array {
if (secretKey?.length !== 64) {
throw new Error('Invalid secretKey, expected 64-bytes');
}
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aToU8a } from '@polkadot/util';
import { vrfVerify } from '@polkadot/wasm-crypto';
@@ -12,7 +10,7 @@ const EMPTY_U8A = new Uint8Array();
* @name sr25519VrfVerify
* @description Verify with sr25519 vrf verification
*/
export function sr25519VrfVerify (message: HexString | Uint8Array | string, signOutput: HexString | string | Uint8Array, publicKey: HexString | Uint8Array | string, context: HexString | string | Uint8Array = EMPTY_U8A, extra: HexString | string | Uint8Array = EMPTY_U8A): boolean {
export function sr25519VrfVerify (message: string | Uint8Array, signOutput: string | Uint8Array, publicKey: string | Uint8Array, context: string | Uint8Array = EMPTY_U8A, extra: string | Uint8Array = EMPTY_U8A): boolean {
const publicKeyU8a = u8aToU8a(publicKey);
const proofU8a = u8aToU8a(signOutput);
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { hasBigInt, u8aToU8a } from '@polkadot/util';
import { isReady, twox } from '@polkadot/wasm-crypto';
@@ -23,7 +21,7 @@ import { xxhash64 } from './xxhash64.js';
* xxhashAsU8a('abc'); // => 0x44bc2cf5ad770999
* ```
*/
export function xxhashAsU8a (data: HexString | Uint8Array | string, bitLength: 64 | 128 | 192 | 256 | 320 | 384 | 448 | 512 = 64, onlyJs?: boolean): Uint8Array {
export function xxhashAsU8a (data: string | Uint8Array, bitLength: 64 | 128 | 192 | 256 | 320 | 384 | 448 | 512 = 64, onlyJs?: boolean): Uint8Array {
const rounds = Math.ceil(bitLength / 64);
const u8a = u8aToU8a(data);
+7 -7
View File
@@ -18,7 +18,7 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "12.3.2",
"version": "12.4.2",
"main": "index.js",
"exports": {
"./hex/toU8a": {
@@ -35,15 +35,15 @@
}
},
"dependencies": {
"@polkadot/x-bigint": "12.3.2",
"@polkadot/x-global": "12.3.2",
"@polkadot/x-textdecoder": "12.3.2",
"@polkadot/x-textencoder": "12.3.2",
"@polkadot/x-bigint": "12.4.2",
"@polkadot/x-global": "12.4.2",
"@polkadot/x-textdecoder": "12.4.2",
"@polkadot/x-textencoder": "12.4.2",
"@types/bn.js": "^5.1.1",
"bn.js": "^5.2.1",
"tslib": "^2.5.3"
"tslib": "^2.6.2"
},
"devDependencies": {
"@polkadot/x-randomvalues": "12.3.2"
"@polkadot/x-randomvalues": "12.4.2"
}
}
+3 -2
View File
@@ -3,6 +3,7 @@
/// <reference types="@polkadot/dev-test/globals.d.ts" />
import { stringify } from '../stringify.js';
import { perf } from '../test/index.js';
import { arrayRange, arrayShuffle } from './index.js';
@@ -30,8 +31,8 @@ describe('arrayShuffle', (): void => {
inp.filter((v) => !out.includes(v))
).toEqual([]);
expect(
JSON.stringify(inp)
).not.toEqual(JSON.stringify(out));
stringify(inp)
).not.toEqual(stringify(out));
});
perf('arrayShuffle', 1000, [[ptest]], arrayShuffle);
+8 -6
View File
@@ -7,7 +7,7 @@ import { BN } from '../bn/index.js';
import { _sqrt2pow53n, nSqrt } from './index.js';
// eslint-disable-next-line jest/no-export
export const SQRT_TESTS: [string | number | BN | bigint, string | number][] = [
export const TESTS: [value: string | number | BN | bigint, expected: string | number][] = [
[0, 0],
[1, 1],
[4, 2],
@@ -47,11 +47,13 @@ describe('nSqrt', (): void => {
).toEqual(true);
});
SQRT_TESTS.forEach(([value, expected], index): void => {
it(`calcs for test #${index}`, (): void => {
expect(
nSqrt(value) === BigInt(expected)
).toEqual(true);
describe('conversion tests', (): void => {
TESTS.forEach(([value, expected], i): void => {
it(`#${i}: calcs ${expected}`, (): void => {
expect(
nSqrt(value) === BigInt(expected)
).toEqual(true);
});
});
});
});
+2 -2
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { BN } from '../bn/bn.js';
import type { HexString, ToBigInt, ToBn } from '../types.js';
import type { ToBigInt, ToBn } from '../types.js';
import { BigInt } from '@polkadot/x-bigint';
@@ -16,7 +16,7 @@ import { isToBn } from '../is/toBn.js';
* @name nToBigInt
* @summary Creates a bigInt value from a BN, bigint, string (base 10 or hex) or number input.
*/
export function nToBigInt <ExtToBn extends ToBigInt | ToBn> (value?: HexString | ExtToBn | BN | bigint | string | number | null): bigint {
export function nToBigInt <ExtToBn extends ToBigInt | ToBn> (value?: ExtToBn | BN | bigint | string | number | null): bigint {
return typeof value === 'bigint'
? value
: !value
+55 -18
View File
@@ -7,9 +7,64 @@ import { arrayRange } from '../array/index.js';
import { perf } from '../test/index.js';
import { nToU8a } from './index.js';
// eslint-disable-next-line jest/no-export
export const TESTS: [isLe: boolean, isNegative: boolean, numarr: number[], strval: string][] = [
// LE, positive numbers
[true, false, [0x12], '18'],
[true, false, [0x12, 0x34], '13330'],
[true, false, [0x12, 0x34, 0x56], '5649426'],
[true, false, [0x12, 0x34, 0x56, 0x78], '2018915346'],
[true, false, [0x12, 0x34, 0x56, 0x78, 0x9a], '663443878930'],
[true, false, [0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc], '207371629900818'],
[true, false, [0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78], '159954953172672629770948536149615195154'],
// LE, positive numbers (w/ signed flag)
[true, true, [12], '12'],
[true, true, [210, 4], '1234'],
[true, true, [64, 226, 1], '123456'],
[true, true, [21, 205, 91, 7], '123456789'],
[true, true, [203, 36, 104, 12, 8], '34567890123'],
[true, true, [255, 159, 114, 78, 24, 9], '9999999999999'],
// LE, negative numbers
[true, true, [244], '-12'],
[true, true, [46, 251], '-1234'],
[true, true, [192, 29, 254], '-123456'],
[true, true, [255, 255, 255, 255], '-1'],
[true, true, [254, 255, 255, 255], '-2'],
[true, true, [235, 50, 164, 248], '-123456789'],
[true, true, [0, 0, 0, 128], '-2147483648'],
[true, true, [0, 0, 0, 240], '-268435456'],
[true, true, [65, 86, 129, 173, 254], '-5678999999'],
[true, true, [1, 96, 141, 177, 231, 246], '-9999999999999'],
[true, true, [1, 0, 156, 88, 76, 73, 31, 242], '-999999999999999999'],
// BE
[false, false, [0x12], '18'],
[false, false, [0x12, 0x34], '4660'],
[false, false, [0x12, 0x34, 0x56], '1193046'],
[false, false, [0x12, 0x34, 0x56, 0x78], '305419896'],
[false, true, [0xf2, 0x34, 0x56, 0x78], '-231451016'],
[false, false, [0x12, 0x34, 0x56, 0x78, 0x9a], '78187493530'],
[false, false, [0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc], '20015998343868'],
[false, false, [0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78], '24197857161011715162171839636988778104']
];
const ptest = arrayRange(65536).map((v) => [v]);
describe('nToU8a', (): void => {
describe('conversion tests', (): void => {
TESTS.forEach(([isLe, isNegative, numarr, strval], i): void => {
const bitLength = numarr.length * 8;
it(`#${i}: converts from ${strval} (bitLength=${bitLength}, isLe=${isLe}, isNegative=${isNegative})`, (): void => {
expect(
nToU8a(
BigInt(strval),
{ bitLength, isLe, isNegative }
)
).toEqual(new Uint8Array(numarr));
});
});
});
it('converts null values to 0x00', (): void => {
expect(
nToU8a(null)
@@ -40,23 +95,5 @@ describe('nToU8a', (): void => {
).toEqual(new Uint8Array([0x56, 0x34, 0x12, 0x00]));
});
it('converts negative numbers', (): void => {
expect(
nToU8a(-1234n, { isNegative: true })
).toEqual(new Uint8Array([46, 251]));
});
it('converts negative numbers (BE)', (): void => {
expect(
nToU8a(-1234n, { isLe: false, isNegative: true })
).toEqual(new Uint8Array([251, 46]));
});
it('converts negative numbers (bitLength)', (): void => {
expect(
nToU8a(-1234n, { bitLength: 32, isNegative: true })
).toEqual(new Uint8Array([46, 251, 255, 255]));
});
perf('nToU8a', 250000, ptest, nToU8a);
});
+3 -2
View File
@@ -14,15 +14,16 @@ const NEG_MASK = BigInt(0xff);
function toU8a (value: bigint, isLe: boolean, isNegative: boolean): Uint8Array {
const arr: number[] = [];
const withSigned = isNegative && (value < _0n);
if (isNegative) {
if (withSigned) {
value = (value + _1n) * -_1n;
}
while (value !== _0n) {
const mod = value % DIV;
const val = Number(
isNegative
withSigned
? mod ^ NEG_MASK
: mod
);
+8 -6
View File
@@ -3,7 +3,7 @@
/// <reference types="@polkadot/dev-test/globals.d.ts" />
import { SQRT_TESTS } from '../bi/sqrt.spec.js';
import { TESTS } from '../bi/sqrt.spec.js';
import { BN, BN_SQRT_MAX_INTEGER, bnSqrt } from './index.js';
describe('bnSqrt', (): void => {
@@ -25,11 +25,13 @@ describe('bnSqrt', (): void => {
).toEqual(true);
});
SQRT_TESTS.forEach(([value, expected], index): void => {
it(`calcs for test #${index}`, (): void => {
expect(
bnSqrt(value).eq(new BN(expected))
).toEqual(true);
describe('conversion tests', (): void => {
TESTS.forEach(([value, expected], i): void => {
it(`#${i}: calcs ${expected}`, (): void => {
expect(
bnSqrt(value).eq(new BN(expected))
).toEqual(true);
});
});
});
});
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString, ToBigInt, ToBn } from '../types.js';
import type { ToBigInt, ToBn } from '../types.js';
import { hexToBn } from '../hex/toBn.js';
import { isBigInt } from '../is/bigInt.js';
@@ -26,7 +26,7 @@ import { BN } from './bn.js';
* bnToBn(new BN(0x1234)); // => BN(0x1234)
* ```
*/
export function bnToBn <ExtToBn extends ToBigInt | ToBn> (value?: HexString | ExtToBn | BN | bigint | string | number | null): BN {
export function bnToBn <ExtToBn extends ToBigInt | ToBn> (value?: ExtToBn | BN | bigint | string | number | null): BN {
return value
? BN.isBN(value)
? value
+12 -58
View File
@@ -4,6 +4,7 @@
/// <reference types="@polkadot/dev-test/globals.d.ts" />
import { arrayRange } from '../array/index.js';
import { TESTS } from '../bi/toU8a.spec.js';
import { perf } from '../test/index.js';
import { BN, bnToU8a } from './index.js';
@@ -40,65 +41,18 @@ describe('bnToU8a', (): void => {
).toEqual(new Uint8Array([0x56, 0x34, 0x12, 0x00]));
});
describe('signed', (): void => {
it('converts negative numbers (BE)', (): void => {
expect(
bnToU8a(new BN(-1234), { isLe: false, isNegative: true })
).toEqual(new Uint8Array([251, 46]));
});
describe('conversion tests', (): void => {
TESTS.forEach(([isLe, isNegative, numarr, strval], i): void => {
const bitLength = numarr.length * 8;
it('converts negative numbers (LE, i8)', (): void => {
expect(
bnToU8a(new BN(-12), { isNegative: true })
).toEqual(new Uint8Array([244]));
});
it('converts negative numbers (LE, i16)', (): void => {
expect(
bnToU8a(new BN(-1234), { isNegative: true })
).toEqual(new Uint8Array([46, 251]));
});
it('converts negative numbers (LE, i24)', (): void => {
expect(
bnToU8a(new BN(-123456), { isNegative: true })
).toEqual(new Uint8Array([192, 29, 254]));
});
it('converts negative numbers (LE, i32)', (): void => {
expect(
bnToU8a(new BN(-123456789), { isNegative: true })
).toEqual(new Uint8Array([235, 50, 164, 248]));
});
it('converts negative numbers (LE, i40)', (): void => {
expect(
bnToU8a(new BN(-5678999999), { isNegative: true })
).toEqual(new Uint8Array([65, 86, 129, 173, 254]));
});
it('converts negative numbers (LE, i48)', (): void => {
expect(
bnToU8a(new BN(-9999999999999), { isNegative: true })
).toEqual(new Uint8Array([1, 96, 141, 177, 231, 246]));
});
it('converts negative numbers (LE, i64)', (): void => {
expect(
bnToU8a(new BN('-999999999999999999'), { isNegative: true })
).toEqual(new Uint8Array([1, 0, 156, 88, 76, 73, 31, 242]));
});
it('converts negative numbers (LE, bitLength)', (): void => {
expect(
bnToU8a(new BN(-1234), { bitLength: 32, isNegative: true })
).toEqual(new Uint8Array([46, 251, 255, 255]));
});
it('converts negative numbers (LE, bitLength, check)', (): void => {
expect(
bnToU8a(new BN(-123456), { bitLength: 32, isNegative: true })
).toEqual(new Uint8Array([192, 29, 254, 255]));
it(`#${i}: converts from ${strval} (bitLength=${bitLength}, isLe=${isLe}, isNegative=${isNegative})`, (): void => {
expect(
bnToU8a(
new BN(strval),
{ bitLength, isLe, isNegative }
)
).toEqual(new Uint8Array(numarr));
});
});
});
+37 -104
View File
@@ -6,83 +6,36 @@
import { BN } from '../bn/index.js';
import { compactToU8a } from './index.js';
const TESTS: [output: string | Uint8Array, input: BN | number][] = [
// Rust tests
// Copied from https://github.com/paritytech/parity-codec/blob/master/src/codec.rs
['00', new BN('0')],
['fc', new BN('63')],
['01 01', new BN('64')],
['fd ff', new BN('16383')],
['02 00 01 00', new BN('16384')],
['fe ff ff ff', new BN('1073741823')],
['03 00 00 00 40', new BN('1073741824')],
['03 ff ff ff ff', new BN(`${1}${'0'.repeat(32)}`, 2).subn(1)],
['07 00 00 00 00 01', new BN(`${1}${'0'.repeat(32)}`, 2)],
['0b 00 00 00 00 00 01', new BN(`${1}${'0'.repeat(40)}`, 2)],
['0f 00 00 00 00 00 00 01', new BN(`${1}${'0'.repeat(48)}`, 2)],
['0f ff ff ff ff ff ff ff', new BN(`${1}${'0'.repeat(56)}`, 2).subn(1)],
['13 00 00 00 00 00 00 00 01', new BN(`${1}${'0'.repeat(56)}`, 2)],
['13 ff ff ff ff ff ff ff ff', new BN(`${1}${'0'.repeat(64)}`, 2).subn(1)],
// own tests
[new Uint8Array([18 << 2]), 18],
[new Uint8Array([0b11111100]), 63],
[new Uint8Array([0xbd, 0x01]), 111],
[new Uint8Array([0b11111101, 0b00000111]), 511],
[new Uint8Array([253, 127]), 0x1fff],
[new Uint8Array([254, 255, 3, 0]), 0xffff],
[new Uint8Array([3 + ((4 - 4) << 2), 249, 255, 255, 255]), 0xfffffff9],
[new Uint8Array([3 + ((6 - 4) << 2), 0x00, 0x40, 0x7a, 0x10, 0xf3, 0x5a]), new BN('00005af3107a4000', 16)],
[new Uint8Array([23, 52, 0x40, 0x7a, 0x10, 0xf3, 0x5a, 0, 0, 18]), new BN('1200005af3107a4034', 16)]
];
describe('encode', (): void => {
it('encodes short u8', (): void => {
expect(
compactToU8a(18)
).toEqual(
new Uint8Array([18 << 2])
);
});
it('encodes max u8 values', (): void => {
expect(
compactToU8a(new BN(63))
).toEqual(
new Uint8Array([0b11111100])
);
});
it('encodes basic u16 value', (): void => {
expect(
compactToU8a(511)
).toEqual(
new Uint8Array([0b11111101, 0b00000111])
);
});
it('encodes basic u16 (not at edge)', (): void => {
expect(
compactToU8a(111)
).toEqual(
new Uint8Array([0xbd, 0x01])
);
});
it('encodes basic u32 values (< 2^30)', (): void => {
expect(
compactToU8a(0x1fff)
).toEqual(
new Uint8Array([253, 127])
);
});
it('encodes basic u32 values (short)', (): void => {
expect(
compactToU8a(0xffff)
).toEqual(
new Uint8Array([254, 255, 3, 0])
);
});
it('encodes basic u32 values (full)', (): void => {
expect(
compactToU8a(0xfffffff9)
).toEqual(
new Uint8Array([3 + ((4 - 4) << 2), 249, 255, 255, 255])
);
});
it('encodes a large value (6 bytes)', (): void => {
expect(
compactToU8a(
new BN('00005af3107a4000', 16)
)
).toEqual(
new Uint8Array([3 + ((6 - 4) << 2), 0x00, 0x40, 0x7a, 0x10, 0xf3, 0x5a])
);
});
it('encodes a large value (9 bytes)', (): void => {
expect(
compactToU8a(
new BN('1200005af3107a4034', 16)
)
).toEqual(
new Uint8Array([23, 52, 0x40, 0x7a, 0x10, 0xf3, 0x5a, 0, 0, 18])
);
});
it('does not modify the original', (): void => {
const original = new BN(123456);
@@ -90,37 +43,17 @@ describe('encode', (): void => {
expect(original.toString()).toEqual('123456');
});
describe('from Rust', (): void => {
// Copied from https://github.com/paritytech/parity-codec/blob/master/src/codec.rs
const testCases = [
{ expected: '00', value: new BN('0') },
{ expected: 'fc', value: new BN('63') },
{ expected: '01 01', value: new BN('64') },
{ expected: 'fd ff', value: new BN('16383') },
{ expected: '02 00 01 00', value: new BN('16384') },
{ expected: 'fe ff ff ff', value: new BN('1073741823') },
{ expected: '03 00 00 00 40', value: new BN('1073741824') },
{ expected: '03 ff ff ff ff', value: new BN(`${1}${'0'.repeat(32)}`, 2).subn(1) },
{ expected: '07 00 00 00 00 01', value: new BN(`${1}${'0'.repeat(32)}`, 2) },
{ expected: '0b 00 00 00 00 00 01', value: new BN(`${1}${'0'.repeat(40)}`, 2) },
{ expected: '0f 00 00 00 00 00 00 01', value: new BN(`${1}${'0'.repeat(48)}`, 2) },
{ expected: '0f ff ff ff ff ff ff ff', value: new BN(`${1}${'0'.repeat(56)}`, 2).subn(1) },
{ expected: '13 00 00 00 00 00 00 00 01', value: new BN(`${1}${'0'.repeat(56)}`, 2) },
{ expected: '13 ff ff ff ff ff ff ff ff', value: new BN(`${1}${'0'.repeat(64)}`, 2).subn(1) }
];
function testEncode (value: BN, expected: string): void {
it(`encodes ${value.toString()}`, (): void => {
describe('conversion tests', (): void => {
TESTS.forEach(([output, input], i): void => {
it(`#${i}: encodes ${input.toString()}`, (): void => {
expect(
compactToU8a(value)
compactToU8a(input)
).toEqual(
Uint8Array.from(
expected.split(' ').map((s): number => parseInt(s, 16))
)
output instanceof Uint8Array
? output
: Uint8Array.from(output.split(' ').map((s) => parseInt(s, 16)))
);
});
}
testCases.forEach(({ expected, value }): void => testEncode(value, expected));
});
});
});
+29 -81
View File
@@ -6,8 +6,32 @@
import { u8aToHex } from '../u8a/index.js';
import { floatToU8a } from './index.js';
class ExtNumber extends Number {
foo = 'bar';
}
class ExtString extends String {
foo = 'bar';
}
// NOTE Hex value outputs created via online conversion tool:
// https://www.h-schmidt.net/FloatConverter/IEEE754.html
// eslint-disable-next-line @typescript-eslint/ban-types
const TESTS: [isLe: boolean | undefined, bitLength: 32 | 64 | undefined, input: String | string | number | Number, output: string][] = [
[undefined, undefined, +0.0, '0x00000000'],
[undefined, undefined, -0.0, '0x00000080'],
[undefined, undefined, 123.456, '0x79e9f642'],
[undefined, undefined, '123.456', '0x79e9f642'],
[undefined, undefined, new ExtNumber(123.456), '0x79e9f642'],
[undefined, undefined, new ExtString(123.456), '0x79e9f642'],
[true, 32, new ExtString(123.456), '0x79e9f642'],
[true, undefined, Number.NaN, '0x0000c07f'],
[false, undefined, -0.0, '0x80000000'],
[undefined, 64, +0.0, '0x0000000000000000'],
[true, 64, -0.0, '0x0000000000000080'],
[false, 64, -0.0, '0x8000000000000000'],
[undefined, 64, Number.NaN, '0x000000000000f87f']
];
describe('floatToU8a', (): void => {
it('throws on invalid bitLength', (): void => {
@@ -16,89 +40,13 @@ describe('floatToU8a', (): void => {
).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 => {
describe('conversion tests', (): void => {
TESTS.forEach(([isLe, bitLength, input, output], i): void => {
it(`#${i}: correctly encodes ${typeof input === 'number' ? input : input.toString()} (typeof=${typeof input})`, (): void => {
expect(
u8aToHex(floatToU8a(123.456))
).toEqual('0x79e9f642');
u8aToHex(floatToU8a(input, { bitLength, isLe }))
).toEqual(output);
});
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';
}
expect(
u8aToHex(floatToU8a(new Test(123.456)))
).toEqual('0x79e9f642');
});
it('encodes String 123.456', (): void => {
class Test extends String {
foo = 'bar';
}
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');
});
});
});
+1 -1
View File
@@ -24,7 +24,7 @@ function formatValue (elapsed: number): string {
* @description Formats an elapsed value into s, m, h or day segments
*/
export function formatElapsed <ExtToBn extends ToBn> (now?: Date | null, value?: bigint | BN | ExtToBn | Date | number | null): string {
const tsNow = (now && now.getTime()) || 0;
const tsNow = now?.getTime() || 0;
const tsValue = value instanceof Date
? value.getTime()
: bnToBn(value).toNumber();
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { BufferObjClass } from './types.js';
import type { BufferClass } from './types.js';
import { BigInt } from '@polkadot/x-bigint';
import { xglobal } from '@polkadot/x-global';
@@ -32,7 +32,7 @@ export const hasWasm = typeof WebAssembly !== 'undefined';
// that some bundlers such as parcel would add (this is a check, not a use)
/** true if the environment has support for Buffer (typically Node.js) */
export const hasBuffer = typeof xglobal.Buffer === 'function' && typeof (xglobal.Buffer as unknown as BufferObjClass).isBuffer === 'function';
export const hasBuffer = typeof xglobal.Buffer === 'function' && typeof (xglobal.Buffer as unknown as BufferClass).isBuffer === 'function';
/** true if the environment has process available (typically Node.js) */
export const hasProcess = typeof xglobal.process === 'object';
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '../types.js';
const CHR = '0123456789abcdef';
const U8 = new Uint8Array(256);
const U16 = new Uint8Array(256 * 256);
@@ -38,7 +36,7 @@ for (let i = 0; i < 256; i++) {
* hexToU8a('0x80001f', 32); // Uint8Array([0x00, 0x80, 0x00, 0x1f])
* ```
*/
export function hexToU8a (value?: HexString | string | null, bitLength = -1): Uint8Array {
export function hexToU8a (value?: string | null, bitLength = -1): Uint8Array {
if (!value) {
return new Uint8Array();
}
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '../types.js';
/**
* @name hexToU8a
* @summary Creates a Uint8Array object from a hex string.
@@ -18,7 +16,7 @@ import type { HexString } from '../types.js';
* hexToU8a('0x80001f', 32); // Uint8Array([0x00, 0x80, 0x00, 0x1f])
* ```
*/
export function hexToU8a (_value?: HexString | string | null, bitLength = -1): Uint8Array {
export function hexToU8a (_value?: string | null, bitLength = -1): Uint8Array {
if (!_value) {
return new Uint8Array();
}
+1 -1
View File
@@ -5,6 +5,6 @@
* @name isArray
* @summary Tests for a Array instance.
*/
export function isArray <T> (value?: unknown): value is Array<T> {
export function isArray <T> (value?: unknown): value is T[] {
return Array.isArray(value);
}
+3 -3
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { BufferObj, BufferObjClass } from '../types.js';
import type { BufferClass, BufferObject } from '../types.js';
import { xglobal } from '@polkadot/x-global';
@@ -22,7 +22,7 @@ import { isFunction } from './function.js';
* console.log('isBuffer', isBuffer(Buffer.from([]))); // => true
* ```
*/
export function isBuffer (value: unknown): value is Buffer {
export function isBuffer <T = BufferObject> (value: unknown): value is T {
// we do check a function first, since it is slightly faster than isBuffer itself
return hasBuffer && !!value && isFunction((value as unknown as BufferObj).readDoubleLE) && (xglobal.Buffer as unknown as BufferObjClass).isBuffer(value);
return hasBuffer && !!value && isFunction((value as unknown as BufferObject).readDoubleLE) && (xglobal.Buffer as unknown as BufferClass).isBuffer(value);
}
+2 -4
View File
@@ -3,10 +3,8 @@
import { stringify } from '../stringify.js';
interface ObjectIndexed {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[index: string]: any;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ObjectIndexed = Record<string, any>;
/**
* @name isJsonObject
+2 -4
View File
@@ -1,10 +1,8 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
interface ObjectIndexed {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[index: string]: any;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ObjectIndexed = Record<string, any>;
/**
* @name isObject
+1 -3
View File
@@ -3,8 +3,6 @@
// Adapted from https://github.com/JulienPalard/is_utf8/blob/master/is_utf8.c
import type { HexString } from '../types.js';
import { u8aToU8a } from '../u8a/toU8a.js';
import { isString } from './string.js';
@@ -14,7 +12,7 @@ import { isString } from './string.js';
* @description
* Checks to see if the input string or Uint8Array is valid Utf8
*/
export function isUtf8 (value?: HexString | number[] | Uint8Array | string | null): boolean {
export function isUtf8 (value?: number[] | Uint8Array | string | null): boolean {
if (!value) {
return isString(value);
}
+2 -2
View File
@@ -1,9 +1,9 @@
// Copyright 2017-2023 @polkadot/types authors & contributors
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
type AnyFn = (...args: unknown[]) => unknown;
type WithToString = { toString: () => string };
interface WithToString { toString: () => string }
/**
* @name lazyMethod
+1 -1
View File
@@ -40,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] && cache[instanceId][stringParams] !== undefined) {
if (cache[instanceId]?.[stringParams] !== undefined) {
delete cache[instanceId][stringParams];
}
};
+1 -1
View File
@@ -34,7 +34,7 @@ describe('objectProperty/objectProperties', (): void => {
b = 1;
get a () {
return 1;
return 1 + 0;
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/util', path: 'auto', type: 'auto', version: '12.3.2' };
export const packageInfo = { name: '@polkadot/util', path: 'auto', type: 'auto', version: '12.4.2' };
+2 -2
View File
@@ -5,7 +5,7 @@
/* global it, expect */
import { formatDecimal, formatNumber } from '../index.js';
import { formatDecimal, formatNumber, stringify } from '../index.js';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ExecFn = (...params: any[]) => unknown;
@@ -85,7 +85,7 @@ ${`${second}:`.padStart(PRE_PAD)} ${t2.toFixed(2).padStart(NUM_PAD)} ms ${t1 > t
expect(
r1.filter((_, i) =>
JSON.stringify(r1[i]) !== JSON.stringify(r2[i])
stringify(r1[i]) !== stringify(r2[i])
)
).toHaveLength(0);
});
+12 -4
View File
@@ -77,20 +77,28 @@ export type HexDigit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
// One day when template strings support regex, we can improve this
export type HexString = `0x${string}`;
// BufferObj interface compatible with Buffer since we don't want to require
// BufferObject interface compatible with Buffer since we don't want to require
// references to the Buffer types from the node typings
export interface BufferObj extends Uint8Array {
//
// Caveat: the references still do sneak in in the d.ts files, specifically
// inside u8a/toBuffer & is/buffer (but not in compiled outputs)
export interface BufferObject extends Uint8Array {
// Possibly used externally via type imports
equals: (otherBuffer: Uint8Array) => boolean;
// As used in is/buffer
readDoubleLE: (offset?: number) => number;
}
// We define a scappy low-level interface to mock Buffer
// (this removes the need for the node typings in built bundles)
export interface BufferObjClass extends Class<BufferObj> {
export interface BufferClass extends Class<BufferObject> {
// As used in u8a/toBuffer
from: <T = BufferObject>(value: unknown) => T;
// As used in is/buffer
isBuffer: (value: unknown) => boolean;
}
export type U8aLike = HexString | number[] | Uint8Array | AnyString;
export type U8aLike = number[] | Uint8Array | AnyString;
export interface Observable {
next: (...params: unknown[]) => unknown;
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '../types.js';
import { u8aToU8a } from './toU8a.js';
/**
@@ -21,7 +19,7 @@ import { u8aToU8a } from './toU8a.js';
* u8aCmp(new Uint8Array([0x69, 0x65]), new Uint8Array([0x68, 0x65])); // +1
* ```
*/
export function u8aCmp (a: HexString | Uint8Array | string, b: HexString | Uint8Array | string): number {
export function u8aCmp (a: string | Uint8Array, b: string | Uint8Array): number {
const u8aa = u8aToU8a(a);
const u8ab = u8aToU8a(b);
let i = 0;
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '../types.js';
import { u8aToU8a } from './toU8a.js';
/**
@@ -19,7 +17,7 @@ import { u8aToU8a } from './toU8a.js';
* u8aEq(new Uint8Array([0x68, 0x65]), new Uint8Array([0x68, 0x65])); // true
* ```
*/
export function u8aEq (a: HexString | Uint8Array | string, b: HexString | Uint8Array | string): boolean {
export function u8aEq (a: string | Uint8Array, b: string | Uint8Array): boolean {
const u8aa = u8aToU8a(a);
const u8ab = u8aToU8a(b);
+36 -258
View File
@@ -3,6 +3,7 @@
/// <reference types="@polkadot/dev-test/globals.d.ts" />
import { TESTS } from '../bi/toU8a.spec.js';
import { perf } from '../test/index.js';
import { u8aToBigInt } from './index.js';
@@ -16,240 +17,6 @@ describe('u8aToBigInt', (): void => {
).toBe('3412');
});
describe('LE', (): void => {
describe('unsigned', (): void => {
it('converts values (u8)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([0x12]),
{ isLe: true }
).toString(16)
).toBe('12');
});
it('converts values (u16)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([0x12, 0x34]),
{ isLe: true }
).toString(16)
).toBe('3412');
});
it('converts values (u24)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([0x12, 0x34, 0x56]),
{ isLe: true }
).toString(16)
).toBe('563412');
});
it('converts values (u32)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([0x12, 0x34, 0x56, 0x78]),
{ isLe: true }
).toString(16)
).toBe('78563412');
});
it('converts values (i32)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([0xf2, 0x34, 0x56, 0x78]),
{ isLe: false, isNegative: true }
).toString(16)
).toBe('-dcba988');
});
it('converts values (u40)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x9a]),
{ isLe: true }
).toString(16)
).toBe('9a78563412');
});
it('converts values (u48)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc]),
{ isLe: true }
).toString(16)
).toBe('bc9a78563412');
});
it('converts values (u128)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78]),
{ isLe: true }
).toString(16)
).toBe('78563412785634127856341278563412');
});
for (let i = 1; i < 32; i++) {
const tu8a = [0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78];
const tstr = tu8a.map((n) => n.toString(16));
it(`converts values with length ${i}`, (): void => {
expect(
u8aToBigInt(
new Uint8Array(tu8a.slice(0, i)),
{ isLe: true }
).toString(16)
).toBe(tstr.slice(0, i).reverse().join(''));
});
}
});
describe('signed', (): void => {
it('converts values (i8)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([244]),
{ isLe: true, isNegative: true }
).toString()
).toBe('-12');
});
it('converts values (i16)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([46, 251]),
{ isLe: true, isNegative: true }
).toString()
).toBe('-1234');
});
it('converts values (i24)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([192, 29, 254]),
{ isLe: true, isNegative: true }
).toString()
).toBe('-123456');
});
it('converts values (i32)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([235, 50, 164, 248]),
{ isLe: true, isNegative: true }
).toString()
).toBe('-123456789');
});
it('converts values (i40)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([65, 86, 129, 173, 254]),
{ isLe: true, isNegative: true }
).toString()
).toBe('-5678999999');
});
it('converts values (i48)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([1, 96, 141, 177, 231, 246]),
{ isLe: true, isNegative: true }
).toString()
).toBe('-9999999999999');
});
it('converts values (i64)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([1, 0, 156, 88, 76, 73, 31, 242]),
{ isLe: true, isNegative: true }
).toString()
).toBe('-999999999999999999');
});
});
});
describe('BE', (): void => {
it('converts values (u8)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([0x12]),
{ isLe: false }
).toString(16)
).toBe('12');
});
it('converts values (u16)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([0x12, 0x34]),
{ isLe: false }
).toString(16)
).toBe('1234');
});
it('converts values (u24)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([0x12, 0x34, 0x56]),
{ isLe: false }
).toString(16)
).toBe('123456');
});
it('converts values (u32)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([0x12, 0x34, 0x56, 0x78]),
{ isLe: false }
).toString(16)
).toBe('12345678');
});
it('converts values (u40)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x9a]),
{ isLe: false }
).toString(16)
).toBe('123456789a');
});
it('converts values (u48)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc]),
{ isLe: false }
).toString(16)
).toBe('123456789abc');
});
it('converts values (u128)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78]),
{ isLe: false }
).toString(16)
).toBe('12345678123456781234567812345678');
});
for (let i = 1; i < 32; i++) {
const tu8a = [0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78];
const tstr = tu8a.map((n) => n.toString(16));
it(`converts values with length ${i}`, (): void => {
expect(
u8aToBigInt(
new Uint8Array(tu8a.slice(0, i)),
{ isLe: false }
).toString(16)
).toBe(tstr.slice(0, i).join(''));
});
}
});
describe('empty creation', (): void => {
it('handles unsigned (le)', (): void => {
expect(
@@ -288,26 +55,6 @@ describe('u8aToBigInt', (): void => {
});
});
describe('negative', (): void => {
it('handles negative numbers (little-endian)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([46, 251]),
{ isLe: true, isNegative: true }
)
).toBe(-1234n);
});
it('handles negative numbers (big-endian)', (): void => {
expect(
u8aToBigInt(
new Uint8Array([251, 46]),
{ isLe: false, isNegative: true }
)
).toBe(-1234n);
});
});
it('handles overflows correctly (little-endian)', (): void => {
expect(
u8aToBigInt(
@@ -317,12 +64,43 @@ describe('u8aToBigInt', (): void => {
).toBe(256n);
});
perf('u8aToBigInt (i32)', 750_000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c])]], (v: Uint8Array) => u8aToBigInt(v, { isNegative: true }));
describe('length tests', (): void => {
[true, false].forEach((isLe) => {
for (let i = 1; i < 32; i++) {
const tu8a = [0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78];
const tstr = tu8a.map((n) => n.toString(16));
it(`converts values with bitLength=${i * 8}, isLe=${isLe}`, (): void => {
expect(
u8aToBigInt(
new Uint8Array(tu8a.slice(0, i)),
{ isLe }
).toString(16)
).toBe(
isLe
? tstr.slice(0, i).reverse().join('')
: tstr.slice(0, i).join('')
);
});
}
});
});
describe('conversion tests', (): void => {
TESTS.forEach(([isLe, isNegative, numarr, strval], i): void => {
it(`#${i}: creates ${strval} (bitLength=${numarr.length * 8}, isLe=${isLe}, isNegative=${isNegative})`, (): void => {
expect(
u8aToBigInt(
new Uint8Array(numarr),
{ isLe, isNegative }
).toString()
).toBe(strval);
});
});
});
perf('u8aToBigInt (i32)', 750_000, [[new Uint8Array([0x9c, 0x9c, 0x9c, 0x9c])]], (v: Uint8Array) => u8aToBigInt(v, { isNegative: true }));
perf('u8aToBigInt (u32)', 750_000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c])]], u8aToBigInt);
perf('u8aToBigInt (u64)', 750_000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x68, 0x65, 0x6c, 0x6c])]], u8aToBigInt);
perf('u8aToBigInt (u128)', 750_000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x68, 0x65, 0x6c, 0x6c, 0x68, 0x65, 0x6c, 0x6c, 0x68, 0x65, 0x6c, 0x6c])]], u8aToBigInt);
// perf('BigInt (constructor)', 1_000_000, [[12345678]], (v: number) => BigInt(v).toString());
// perf('BigInt (constructor -> string)', 1_000_000, [[12345678]], (v: number) => BigInt(v).toString());
});
+18 -16
View File
@@ -16,28 +16,30 @@ const U64_MAX = BigInt('0x10000000000000000');
* @summary Creates a BigInt from a Uint8Array object.
*/
export function u8aToBigInt (value: Uint8Array, { isLe = true, isNegative = false }: ToBnOptions = {}): bigint {
// BE is not the optimal path - LE is the SCALE default
const u8a = isLe
? value
: value.slice().reverse();
const count = u8a.length;
// slice + reverse is expensive, however SCALE is LE by default so this is the path
// we are most interested in (the BE is added for the sake of being comprehensive)
if (!isLe) {
value = value.slice().reverse();
}
if (isNegative) {
const count = value.length;
if (isNegative && count && (value[count - 1] & 0x80)) {
switch (count) {
case 0:
return BigInt(0);
case 1:
return BigInt(((u8a[0] ^ 0x0000_00ff) * -1) - 1);
return BigInt(((value[0] ^ 0x0000_00ff) * -1) - 1);
case 2:
return BigInt((((u8a[0] + (u8a[1] << 8)) ^ 0x0000_ffff) * -1) - 1);
return BigInt((((value[0] + (value[1] << 8)) ^ 0x0000_ffff) * -1) - 1);
case 4:
return BigInt((((u8a[0] + (u8a[1] << 8) + (u8a[2] << 16) + (u8a[3] * 0x1_00_00_00)) ^ 0xffff_ffff) * -1) - 1);
return BigInt((((value[0] + (value[1] << 8) + (value[2] << 16) + (value[3] * 0x1_00_00_00)) ^ 0xffff_ffff) * -1) - 1);
}
const dvI = new DataView(u8a.buffer, u8a.byteOffset);
const dvI = new DataView(value.buffer, value.byteOffset);
if (count === 8) {
return dvI.getBigInt64(0, true);
@@ -51,7 +53,7 @@ export function u8aToBigInt (value: Uint8Array, { isLe = true, isNegative = fals
}
if (mod) {
result = (result * U8_MAX) + BigInt(u8a[0] ^ 0xff);
result = (result * U8_MAX) + BigInt(value[0] ^ 0xff);
}
return (result * -_1n) - _1n;
@@ -62,16 +64,16 @@ export function u8aToBigInt (value: Uint8Array, { isLe = true, isNegative = fals
return BigInt(0);
case 1:
return BigInt(u8a[0]);
return BigInt(value[0]);
case 2:
return BigInt(u8a[0] + (u8a[1] << 8));
return BigInt(value[0] + (value[1] << 8));
case 4:
return BigInt(u8a[0] + (u8a[1] << 8) + (u8a[2] << 16) + (u8a[3] * 0x1_00_00_00));
return BigInt(value[0] + (value[1] << 8) + (value[2] << 16) + (value[3] * 0x1_00_00_00));
}
const dvI = new DataView(u8a.buffer, u8a.byteOffset);
const dvI = new DataView(value.buffer, value.byteOffset);
switch (count) {
case 8:
@@ -89,7 +91,7 @@ export function u8aToBigInt (value: Uint8Array, { isLe = true, isNegative = fals
}
if (mod) {
result = (result * U8_MAX) + BigInt(u8a[0]);
result = (result * U8_MAX) + BigInt(value[0]);
}
return result;
+36 -259
View File
@@ -3,7 +3,7 @@
/// <reference types="@polkadot/dev-test/globals.d.ts" />
// import { BN } from '../bn/index.js';
import { TESTS } from '../bi/toU8a.spec.js';
import { perf } from '../test/index.js';
import { u8aToBn } from './index.js';
@@ -17,240 +17,6 @@ describe('u8aToBn', (): void => {
).toBe('3412');
});
describe('LE', (): void => {
describe('unsigned', (): void => {
it('converts values (u8)', (): void => {
expect(
u8aToBn(
new Uint8Array([0x12]),
{ isLe: true }
).toString(16)
).toBe('12');
});
it('converts values (u16)', (): void => {
expect(
u8aToBn(
new Uint8Array([0x12, 0x34]),
{ isLe: true }
).toString(16)
).toBe('3412');
});
it('converts values (u24)', (): void => {
expect(
u8aToBn(
new Uint8Array([0x12, 0x34, 0x56]),
{ isLe: true }
).toString(16)
).toBe('563412');
});
it('converts values (u32)', (): void => {
expect(
u8aToBn(
new Uint8Array([0x12, 0x34, 0x56, 0x78]),
{ isLe: true }
).toString(16)
).toBe('78563412');
});
it('converts values (u40)', (): void => {
expect(
u8aToBn(
new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x9a]),
{ isLe: true }
).toString(16)
).toBe('9a78563412');
});
it('converts values (u48)', (): void => {
expect(
u8aToBn(
new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc]),
{ isLe: true }
).toString(16)
).toBe('bc9a78563412');
});
it('converts values (u128)', (): void => {
expect(
u8aToBn(
new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78]),
{ isLe: true }
).toString(16)
).toBe('78563412785634127856341278563412');
});
for (let i = 1; i < 32; i++) {
const tu8a = [0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78];
const tstr = tu8a.map((n) => n.toString(16));
it(`converts values with length ${i}`, (): void => {
expect(
u8aToBn(
new Uint8Array(tu8a.slice(0, i)),
{ isLe: true }
).toString(16)
).toBe(tstr.slice(0, i).reverse().join(''));
});
}
});
describe('signed', (): void => {
it('converts values (i8)', (): void => {
expect(
u8aToBn(
new Uint8Array([244]),
{ isLe: true, isNegative: true }
).toString()
).toBe('-12');
});
it('converts values (i16)', (): void => {
expect(
u8aToBn(
new Uint8Array([46, 251]),
{ isLe: true, isNegative: true }
).toString()
).toBe('-1234');
});
it('converts values (i24)', (): void => {
expect(
u8aToBn(
new Uint8Array([192, 29, 254]),
{ isLe: true, isNegative: true }
).toString()
).toBe('-123456');
});
it('converts values (i32)', (): void => {
expect(
u8aToBn(
new Uint8Array([235, 50, 164, 248]),
{ isLe: true, isNegative: true }
).toString()
).toBe('-123456789');
});
it('converts values (i40)', (): void => {
expect(
u8aToBn(
new Uint8Array([65, 86, 129, 173, 254]),
{ isLe: true, isNegative: true }
).toString()
).toBe('-5678999999');
});
it('converts values (i48)', (): void => {
expect(
u8aToBn(
new Uint8Array([1, 96, 141, 177, 231, 246]),
{ isLe: true, isNegative: true }
).toString()
).toBe('-9999999999999');
});
it('converts values (i64)', (): void => {
expect(
u8aToBn(
new Uint8Array([1, 0, 156, 88, 76, 73, 31, 242]),
{ isLe: true, isNegative: true }
).toString()
).toBe('-999999999999999999');
});
});
});
describe('BE', (): void => {
it('converts values (u8)', (): void => {
expect(
u8aToBn(
new Uint8Array([0x12]),
{ isLe: false }
).toString(16)
).toBe('12');
});
it('converts values (u16)', (): void => {
expect(
u8aToBn(
new Uint8Array([0x12, 0x34]),
{ isLe: false }
).toString(16)
).toBe('1234');
});
it('converts values (u24)', (): void => {
expect(
u8aToBn(
new Uint8Array([0x12, 0x34, 0x56]),
{ isLe: false }
).toString(16)
).toBe('123456');
});
it('converts values (u32)', (): void => {
expect(
u8aToBn(
new Uint8Array([0x12, 0x34, 0x56, 0x78]),
{ isLe: false }
).toString(16)
).toBe('12345678');
});
it('converts values (i32)', (): void => {
expect(
u8aToBn(
new Uint8Array([0xf2, 0x34, 0x56, 0x78]),
{ isLe: false, isNegative: true }
).toString(16)
).toBe('-dcba988');
});
it('converts values (u40)', (): void => {
expect(
u8aToBn(
new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x9a]),
{ isLe: false }
).toString(16)
).toBe('123456789a');
});
it('converts values (u48)', (): void => {
expect(
u8aToBn(
new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc]),
{ isLe: false }
).toString(16)
).toBe('123456789abc');
});
it('converts values (u128)', (): void => {
expect(
u8aToBn(
new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78]),
{ isLe: false }
).toString(16)
).toBe('12345678123456781234567812345678');
});
for (let i = 1; i < 32; i++) {
const tu8a = [0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78];
const tstr = tu8a.map((n) => n.toString(16));
it(`converts values with length ${i}`, (): void => {
expect(
u8aToBn(
new Uint8Array(tu8a.slice(0, i)),
{ isLe: false }
).toString(16)
).toBe(tstr.slice(0, i).join(''));
});
}
});
describe('empty creation', (): void => {
it('handles unsigned (le)', (): void => {
expect(
@@ -289,26 +55,6 @@ describe('u8aToBn', (): void => {
});
});
describe('negative', (): void => {
it('handles negative numbers (little-endian)', (): void => {
expect(
u8aToBn(
new Uint8Array([46, 251]),
{ isLe: true, isNegative: true }
).toNumber()
).toBe(-1234);
});
it('handles negative numbers (big-endian)', (): void => {
expect(
u8aToBn(
new Uint8Array([251, 46]),
{ isLe: false, isNegative: true }
).toNumber()
).toBe(-1234);
});
});
it('handles overflows correctly (little-endian)', (): void => {
expect(
u8aToBn(
@@ -318,12 +64,43 @@ describe('u8aToBn', (): void => {
).toBe(256);
});
perf('u8aToBn (i32)', 750_000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c])]], (v: Uint8Array) => u8aToBn(v, { isNegative: true }));
describe('length tests', (): void => {
[true, false].forEach((isLe) => {
for (let i = 1; i < 32; i++) {
const tu8a = [0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78];
const tstr = tu8a.map((n) => n.toString(16));
it(`converts values with bitLength=${i * 8}, isLe=${isLe}`, (): void => {
expect(
u8aToBn(
new Uint8Array(tu8a.slice(0, i)),
{ isLe }
).toString(16)
).toBe(
isLe
? tstr.slice(0, i).reverse().join('')
: tstr.slice(0, i).join('')
);
});
}
});
});
describe('conversion tests', (): void => {
TESTS.forEach(([isLe, isNegative, numarr, strval], i): void => {
it(`#${i}: creates ${strval} (bitLength=${numarr.length * 8}, isLe=${isLe}, isNegative=${isNegative})`, (): void => {
expect(
u8aToBn(
new Uint8Array(numarr),
{ isLe, isNegative }
).toString()
).toBe(strval);
});
});
});
perf('u8aToBn (i32)', 750_000, [[new Uint8Array([0x9c, 0x9c, 0x9c, 0x9c])]], (v: Uint8Array) => u8aToBn(v, { isNegative: true }));
perf('u8aToBn (u32)', 750_000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c])]], u8aToBn);
perf('u8aToBn (u64)', 750_000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x68, 0x65, 0x6c, 0x6c])]], u8aToBn);
perf('u8aToBn (u128)', 750_000, [[new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x68, 0x65, 0x6c, 0x6c, 0x68, 0x65, 0x6c, 0x6c, 0x68, 0x65, 0x6c, 0x6c])]], u8aToBn);
// perf('BN (constructor)', 1_000_000, [[12345678]], (v: number) => new BN(v));
// perf('BN (constructor -> string)', 1_000_000, [[12345678]], (v: number) => new BN(v).toString());
});
+47 -73
View File
@@ -24,104 +24,78 @@ import { BN } from '../bn/bn.js';
* ```
*/
export function u8aToBn (value: Uint8Array, { isLe = true, isNegative = false }: ToBnOptions = {}): BN {
// slice + reverse is expensive, however SCALE is LE by default so this is the path
// we are most interested in (the BE is added for the sake of being comprehensive)
if (!isLe) {
value = value.slice().reverse();
}
const count = value.length;
// shortcut for <= u48 values - in this case the manual conversion
// here seems to be more efficient than passing the full array
if (isNegative) {
if (isLe) {
// Most common case i{8, 16, 32} default LE SCALE-encoded
// For <= 32, we also optimize the xor to a single op
switch (count) {
case 0:
return new BN(0);
case 1:
return new BN(((value[0] ^ 0x0000_00ff) * -1) - 1);
case 2:
return new BN((((value[0] + (value[1] << 8)) ^ 0x0000_ffff) * -1) - 1);
case 3:
return new BN((((value[0] + (value[1] << 8) + (value[2] << 16)) ^ 0x00ff_ffff) * -1) - 1);
case 4:
// for the 3rd byte, we don't << 24 - since JS converts all bitwise operators to
// 32-bit, in the case where the top-most bit is set this yields a negative value
return new BN((((value[0] + (value[1] << 8) + (value[2] << 16) + (value[3] * 0x1_00_00_00)) ^ 0xffff_ffff) * -1) - 1);
case 5:
return new BN(((((value[0] + (value[1] << 8) + (value[2] << 16) + (value[3] * 0x1_00_00_00)) ^ 0xffff_ffff) + ((value[4] ^ 0xff) * 0x1_00_00_00_00)) * -1) - 1);
case 6:
return new BN(((((value[0] + (value[1] << 8) + (value[2] << 16) + (value[3] * 0x1_00_00_00)) ^ 0xffff_ffff) + (((value[4] + (value[5] << 8)) ^ 0x0000_ffff) * 0x1_00_00_00_00)) * -1) - 1);
default:
return new BN(value, 'le').fromTwos(value.length * 8);
}
}
if (count === 0) {
return new BN(0);
} else if (count > 6) {
return new BN(value, 'be').fromTwos(value.length * 8);
}
let result = 0;
for (let i = 0; i < count; i++) {
result = (result * 0x1_00) + (value[i] ^ 0xff);
}
return new BN((result * -1) - 1);
}
if (isLe) {
// Most common case - u{8, 16, 32} default LE SCALE-encoded
//
// There are some slight benefits in unrolling this specific loop,
// however it comes with diminishing returns since here the actual
// `new BN` does seem to take up the bulk of the time
if (isNegative && count && (value[count - 1] & 0x80)) {
// Most common case i{8, 16, 32} default LE SCALE-encoded
// For <= 32, we also optimize the xor to a single op
switch (count) {
case 0:
return new BN(0);
case 1:
return new BN(value[0]);
return new BN(((value[0] ^ 0x0000_00ff) * -1) - 1);
case 2:
return new BN(value[0] + (value[1] << 8));
return new BN((((value[0] + (value[1] << 8)) ^ 0x0000_ffff) * -1) - 1);
case 3:
return new BN(value[0] + (value[1] << 8) + (value[2] << 16));
return new BN((((value[0] + (value[1] << 8) + (value[2] << 16)) ^ 0x00ff_ffff) * -1) - 1);
case 4:
// for the 3rd byte, we don't << 24 - since JS converts all bitwise operators to
// 32-bit, in the case where the top-most bit is set this yields a negative value
return new BN(value[0] + (value[1] << 8) + (value[2] << 16) + (value[3] * 0x1_00_00_00));
return new BN((((value[0] + (value[1] << 8) + (value[2] << 16) + (value[3] * 0x1_00_00_00)) ^ 0xffff_ffff) * -1) - 1);
case 5:
return new BN(value[0] + (value[1] << 8) + (value[2] << 16) + ((value[3] + (value[4] << 8)) * 0x1_00_00_00));
return new BN(((((value[0] + (value[1] << 8) + (value[2] << 16) + (value[3] * 0x1_00_00_00)) ^ 0xffff_ffff) + ((value[4] ^ 0xff) * 0x1_00_00_00_00)) * -1) - 1);
case 6:
return new BN(value[0] + (value[1] << 8) + (value[2] << 16) + ((value[3] + (value[4] << 8) + (value[5] << 16)) * 0x1_00_00_00));
return new BN(((((value[0] + (value[1] << 8) + (value[2] << 16) + (value[3] * 0x1_00_00_00)) ^ 0xffff_ffff) + (((value[4] + (value[5] << 8)) ^ 0x0000_ffff) * 0x1_00_00_00_00)) * -1) - 1);
default:
return new BN(value, 'le');
return new BN(value, 'le').fromTwos(count * 8);
}
}
if (count === 0) {
return new BN(0);
} else if (count > 6) {
return new BN(value, 'be');
// Most common case - u{8, 16, 32} default LE SCALE-encoded
//
// There are some slight benefits in unrolling this specific loop,
// however it comes with diminishing returns since here the actual
// `new BN` does seem to take up the bulk of the time
switch (count) {
case 0:
return new BN(0);
case 1:
return new BN(value[0]);
case 2:
return new BN(value[0] + (value[1] << 8));
case 3:
return new BN(value[0] + (value[1] << 8) + (value[2] << 16));
case 4:
// for the 3rd byte, we don't << 24 - since JS converts all bitwise operators to
// 32-bit, in the case where the top-most bit is set this yields a negative value
return new BN(value[0] + (value[1] << 8) + (value[2] << 16) + (value[3] * 0x1_00_00_00));
case 5:
return new BN(value[0] + (value[1] << 8) + (value[2] << 16) + ((value[3] + (value[4] << 8)) * 0x1_00_00_00));
case 6:
return new BN(value[0] + (value[1] << 8) + (value[2] << 16) + ((value[3] + (value[4] << 8) + (value[5] << 16)) * 0x1_00_00_00));
default:
return new BN(value, 'le');
}
let result = 0;
for (let i = 0; i < count; i++) {
result = (result * 0x1_00) + value[i];
}
return new BN(result);
}
+11 -3
View File
@@ -1,6 +1,12 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { BufferClass, BufferObject } from '../types.js';
import { xglobal } from '@polkadot/x-global';
import { hasBuffer } from '../has.js';
/**
* @name u8aToBuffer
* @summary Creates a Buffer object from a hex string.
@@ -12,9 +18,11 @@
* ```javascript
* import { u8aToBuffer } from '@polkadot/util';
*
* console.log('Buffer', u8aToBuffer('0x123480001f'));
* console.log('Buffer', u8aToBuffer(new Uint8Array([1, 2, 3])));
* ```
*/
export function u8aToBuffer (value?: Uint8Array | null): Buffer {
return Buffer.from(value || []);
export function u8aToBuffer <T = BufferObject> (value?: Uint8Array | null): T {
return hasBuffer
? (xglobal.Buffer as unknown as BufferClass).from(value || [])
: new Uint8Array(value || []) as T;
}
+1 -1
View File
@@ -54,7 +54,7 @@ export function u8aToHex (value?: Uint8Array | null, bitLength = -1, isPrefixed
? '0x'
: '' as HexString;
if (!value || !value.length) {
if (!value?.length) {
return empty;
} else if (bitLength > 0) {
const length = Math.ceil(bitLength / 8);

Some files were not shown because too many files have changed in this diff Show More