Compare commits

..
46 Commits
Author SHA1 Message Date
Github Actions cd20fe6c8b [CI Skip] release/stable 2.13.1
skip-checks: true
2020-06-08 14:03:31 +00:00
Jaco Greeff 28f8ca73aa 2.13 (#616) 2020-06-08 15:59:47 +02:00
Github Actions f4a8bfc0c0 [CI Skip] release/beta 2.13.0-beta.5
skip-checks: true
2020-06-08 12:33:10 +00:00
Jaco Greeff 94b058d6a3 Align bnToHex signature with bnToU8a (#615) 2020-06-08 14:29:40 +02:00
Github Actions 3d7ddb85a2 [CI Skip] release/beta 2.13.0-beta.4
skip-checks: true
2020-06-08 11:35:08 +00:00
Jaco Greeff f7a2bb895f Fix blake2 U8a JS with hex inputs (#614)
* Fix blake2 U8a JS with hex inputs

* Apply suggestions from code review
2020-06-08 13:31:10 +02:00
Github Actions c1bfcc00b6 [CI Skip] release/beta 2.13.0-beta.3
skip-checks: true
2020-06-06 08:08:42 +00:00
Jaco Greeff b16d8e7c26 Bump deps (#612) 2020-06-06 10:05:02 +02:00
Github Actions 2a4b363fcd [CI Skip] release/beta 2.13.0-beta.2
skip-checks: true
2020-06-05 20:17:13 +00:00
Jaco Greeff de689b8e6f Bump deps (#611) 2020-06-05 22:13:55 +02:00
Github Actions 2e72ab920b [CI Skip] release/beta 2.13.0-beta.1
skip-checks: true
2020-06-02 09:44:29 +00:00
Jaco Greeff 565e6baecd Linting 2020-06-02 11:40:25 +02:00
Jaco Greeff 1e15203b6c Reset to beta 2020-06-02 11:24:23 +02:00
Github Actions cc8639565d [CI Skip] release/stable 2.12.2
skip-checks: true
2020-06-02 08:31:51 +00:00
Jaco Greeff b77d2e6860 Linting 2020-06-02 10:28:25 +02:00
Jaco Greeff e1fbd8ff9f 2.12.2 2020-06-02 10:22:30 +02:00
Github Actions f56dd32b4a [CI Skip] release/stable 2.12.1
skip-checks: true
2020-06-01 16:09:53 +00:00
Jaco Greeff 6077bef570 2.12 (#609) 2020-06-01 18:05:55 +02:00
Github Actions 377d83d4ed [CI Skip] release/beta 2.12.0-beta.2
skip-checks: true
2020-06-01 08:31:12 +00:00
Jaco Greeff bdb14f91a8 Pre-checks on verify input lengths (#608)
* Pre-checks on verify input lengths

* Small cleanup

* Update error signatures
2020-06-01 10:27:08 +02:00
Github Actions cc5b7ed0ad [CI Skip] release/beta 2.12.0-beta.1
skip-checks: true
2020-06-01 07:33:27 +00:00
Jaco Greeff d4491aeb7f Small cleanups, u8aConcat optimization (#607)
* Small cleanups, u8aConcat oprimizations

* Cleanup

* Pre-allocate arrays

* Don't recreate PREFIX
2020-06-01 09:29:44 +02:00
Github Actions 0f6e996799 [CI Skip] release/beta 2.12.0-beta.0
skip-checks: true
2020-05-31 12:22:47 +00:00
Jaco Greeff 1f3dd60a8d {address,u8a}Eq functions (#606)
* {addres,u8a}Eq functions

* Remove mnemonicToSeed
2020-05-31 14:19:10 +02:00
Github Actions 3351fb1cba [CI Skip] 2.11.1
skip-checks: true
2020-05-26 07:00:59 +00:00
Jaco Greeff 32d176e424 2.11 (#604) 2020-05-26 08:57:31 +02:00
Github Actions aec1e26cb9 [CI Skip] 2.11.0-beta.2
skip-checks: true
2020-05-24 17:08:04 +00:00
Jaco Greeff 7d529b6c93 Type adjustments for meta 2020-05-24 19:04:15 +02:00
Github Actions e22b39ae01 [CI Skip] 2.11.0-beta.1
skip-checks: true
2020-05-23 12:26:33 +00:00
Jaco Greeff 18a202c460 Bump dev w/ eslint (#603)
* Bump dev w/ eslint

* Mop-up remaining lint issues

* Update stringShorten expectation
2020-05-23 14:23:13 +02:00
Github Actions fd9ce319a5 [CI Skip] 2.11.0-beta.0
skip-checks: true
2020-05-15 10:37:46 +00:00
Jaco Greeff a04c0a5e82 Bump deps (#601) 2020-05-15 12:34:22 +02:00
Github Actions 06cb5e57a0 [CI Skip] 2.10.1
skip-checks: true
2020-05-14 05:42:04 +00:00
Jaco Greeff 103ea045bf 2.10 (#599) 2020-05-14 07:38:43 +02:00
Github Actions 4315c76814 [CI Skip] 2.10.0-beta.5
skip-checks: true
2020-05-11 12:01:35 +00:00
Jaco Greeff 6de6b871cd Adjust DeriveJunction (types & BigInt) (#598) 2020-05-11 13:57:59 +02:00
Github Actions 82e5d76821 [CI Skip] 2.10.0-beta.4
skip-checks: true
2020-05-11 09:58:13 +00:00
Jaco Greeff d9a18a4acf Bump berry (#597) 2020-05-11 11:54:45 +02:00
Github Actions 2d1d4f808e [CI Skip] 2.10.0-beta.3
skip-checks: true
2020-05-11 08:00:19 +00:00
Jaco Greeff d1de30907f TextEncoder allows non-Uint8Array Buffers (#596)
* TextEncoder allows non-Uint8Array Buffers

* Add eslintrc to eslintignore
2020-05-11 09:57:00 +02:00
Github Actions d3583dc432 [CI Skip] 2.10.0-beta.2
skip-checks: true
2020-05-08 18:15:33 +00:00
Wei Tang bb04fa28f7 ss58: add Kulupu prefix to the list (#595) 2020-05-08 20:12:17 +02:00
Github Actions bd8e862b62 [CI Skip] 2.10.0-beta.1
skip-checks: true
2020-04-30 06:06:24 +00:00
Jaco Greeff 0f45b7fbf3 Bump deps (#594) 2020-04-30 08:03:20 +02:00
Github Actions 03eb72f128 [CI Skip] 2.10.0-beta.0
skip-checks: true
2020-04-30 05:31:32 +00:00
Jaco Greeff f76a4a98be beta bump (#593) 2020-04-30 07:28:35 +02:00
104 changed files with 5198 additions and 3979 deletions
+1 -1
View File
@@ -1,2 +1,2 @@
5
2.6.2
2.6.22.12.2
+1
View File
@@ -1,3 +1,4 @@
.eslintrc.js
**/build/*
**/coverage/*
**/node_modules/*
+2 -5
View File
@@ -10,7 +10,7 @@ jobs:
matrix:
step: ['build:release', 'docs:release']
name: ${{ matrix.step }}
if: "! contains(github.event.head_commit.message, '[CI Skip]') && github.repository == 'polkadot-js/common'"
if: "! startsWith(github.event.head_commit.message, '[CI Skip]') && github.repository == 'polkadot-js/common'"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
@@ -21,16 +21,13 @@ jobs:
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
GH_PAGES_SRC: build-docs
GH_PAT: ${{ secrets.GH_PAT }}
GH_TOKEN: ${{ secrets.GH_PAT }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_RELEASE_GITHUB_API_TOKEN: ${{ secrets.GH_PAT }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
yarn install --immutable | grep -v 'YN0013'
yarn ${{ matrix.step }}
dummy:
name: Dummy
if: "contains(github.event.head_commit.message, '[CI Skip]')"
runs-on: ubuntu-latest
steps:
- name: dummy
+14 -8
View File
File diff suppressed because one or more lines are too long
+99 -67
View File
@@ -1,22 +1,54 @@
# 2.9.1 Apr 23, 2020
# CHANGELOG
## 2.13.1 Jun 8, 2020
- Fix JS blake2 fallback (non-wasm) to correctly deal with hex inputs
- Align `bnToHex` signature with `bnToU8a` (with old/new style)
- Allow `bnTo{Hex,U8a}` to take any value with `.toBn()` signatures
## 2.12.2 Jun 1, 2020
- Fix `isFunction` signature to assert `Function`
## 2.12.1 Jun 1, 2020
- **Important** Removed `mnemonicToSeed`, it is only for bip39, use `mnemonicToMiniSecret` for the Substrate variant
- Added `u8aEq` to compare two Uint8Array or hex values for an exact match
- Added `addressEq` to compare two addresses (ss58, Uint8array or hex) for an exact match
- Throw error on `{nacl,schnorrkel}Verify` on invalid input lengths
- Performance optimizations in `u8aToHex` & `u8aConcat`
## 2.11.1 May 26, 2020
- Internal cleanups on typings
- Support for latest TypeScript, eslint & typescript-eslint
## 2.10.1 May 14, 2020
- Add Kulupu ss58 prefix as an allowed value (Thanks to https://github.com/sorpaas)
- Make the `TextEncoder` polyfill handle non-compliant Buffer implementations (newer versions of Jest)
- `DeriveJunction` now also allows for BigInt values (aligning with number types elsewhere)
- Small code-flow optimizations
## 2.9.1 Apr 30, 2020
- Add support for ECDSA keypairs (Thanks to https://github.com/akru)
- Added `createKeyMulti` & `createKeySub` to create utility sub & multi keys
- Added `u8aSorted` to sort `Uint8Arrays`
- Added `sortAddresses` to sort addresses based on their internal representation
# 2.8.1 Apr 9, 2020
## 2.8.1 Apr 9, 2020
- Keypair will now throw an error when attempting to sign/derive using a locked pair (Thanks to https://github.com/h4x3rotab)
- Cleanup `isDevelopment` regex to cater for chains such as `Westend Development`
# 2.7.1 Mar 31, 2020
## 2.7.1 Mar 31, 2020
- Add `bnSqrt` to calculate the integer sqrt via Newton iteration
- Allow for optional wasm-crypto, specifically via `@polkadot/util-crypto/noWasm`
- Misc. CI infrastructure cleanups
# 2.6.1 Feb 29, 2020
## 2.6.1 Feb 29, 2020
- **Breaking change** Following on the 2.0 release, `@polkadot/wasm` was updated to 1.1+. sr25510 now only verifies 0.8+ signatures, closing the loop on dropping Substrate 1.x-era support
- Add `signatureVerify (message: Uint8Array | string, signature: Uint8Array | string, addressOrPublicKey: Uint8Array | string): VerifyResult` to verify any signature, regardless of type. Returns validity & detected crypto type.
@@ -24,14 +56,14 @@
- Add `addressCheckChecksum (decoded: Uint8Array)` as an helper to extract and verify the ss58 checksum
- Swap to yarn 2, allow use in yarn 2 projects
# 2.5.1 Feb 22, 2020
## 2.5.1 Feb 22, 2020
- **Breaking change** (TypeScript only) The `*.d.ts` files now contain TypeScript 3.8 features, `#private`, which is not usable in older versions
- Add `isBigInt(value)` to allow `BigInt` checks. Also add support in `bnToBn` as well as number conversion utils
- Add `isChildClass(Parent, Child?)` to check if a class extends the parent, asserting Child is Parent
- (internal) Use `#<field>` instead of `private _<field>` for private class variables
# 2.4.1 Feb 18, 2020
## 2.4.1 Feb 18, 2020
- Ensure that `formatBalance` does not apply unit overrides apply when no SI is applicable
- Adjust `formatBalance(<balance>, <options>)` to take expanded `withUnit: string | boolean` option where string is an actual unit, e.g. `KSM`
@@ -39,22 +71,22 @@
- The `.setSS58Format` on keyring will now just operate on pairs created on the keyring, not globally. The global `setSS58Format` in `@polkadot/util-crypto` will be deprecated.
- The deprecated `addressPrefix` option to keyring has been belatedly removed (Use `ss58Format` rather)
# 2.3.1 Feb 15, 2020
## 2.3.1 Feb 15, 2020
- Remove dependency on moment.js with `formatDate` function (Thanks to https://github.com/AndreasGassmann)
- Move TypeScript `@types/*` to dev deps (Thanks to https://github.com/AndreasGassmann)
- Update to `@polkadot/wasm-crypto` 1.0
- Cleanup dependencies to pave the way for using yarn 2 (Explicit instead of implicit)
# 2.2.1 Feb 06, 2020
## 2.2.1 Feb 06, 2020
- Add resolver for jest requires (tests from src)
# 2.1.1 Feb 04, 2020
## 2.1.1 Feb 04, 2020
- Update `detectPackage(<package.json>, __dirname?)` with calling folder
# 2.0.1 Jan 30, 2020
## 2.0.1 Jan 30, 2020
- Update w3f/schnorrkel to 0.8.5 (Full Substrate 2.x support, no 1.x support)
- Remove Alice session (ed2551) account from testing keyring (not applicable to Substrate 2.x)
@@ -62,27 +94,27 @@
- Renamed `assertSingletonPackage` to `detectPackage` with inclusion of version listing
- Swap to elliptic library for secp2561 recovery (No node bindings)
# 1.8.1 Jan 09, 2020
## 1.8.1 Jan 09, 2020
- Add cross-client encryption/decryption support (Thanks to https://github.com/hskang9)
# 1.7.1 Nov 27, 2019
## 1.7.1 Nov 27, 2019
- `formatBalance` signature now allows to force unit displays
- Keypair now allows for derive on a pair, with `pair.derive(...)`
- `assert` now acts like a real asserts, with no return - signature adapted for new TS 3.7
# 1.6.1 Oct 24, 2019
## 1.6.1 Oct 24, 2019
- `pair.sign(message)` now takes an optional second `options?: SignOptions` parameter, where `SignOptions` is currently defined as `{ withType: boolean }`. Here `withType` instructs the signing to prepend the type of signature (ed2551, sr25519 or ecdsa). This is used for the new Polkadot/Substrate MultiSignature format.
# 1.5.1 Sep 25, 2019
## 1.5.1 Sep 25, 2019
- Fix typings on the Keyring-exposed encode & decodeAddress
- Allow ss58Format = 0 as a valid value
- Loosen type definitions for allowed ss58format values (still checked against allowed array)
# 1.4.1 Sep 12, 2019
## 1.4.1 Sep 12, 2019
- **Breaking change** To set the `ss58Format`, you should now use `setSS58Format` as opposed to the old `setAddressPrefix`
- Renamed `keyring.setAddressPrefix` to `keyring.setSS58Format`
@@ -90,25 +122,25 @@
- Added `stringToHex` and `hexToString` conversion utilities to `@polkadot/util`
- Swap to [Babel 7.6.0](https://babeljs.io/) for all compilation, for latest improvements in code generation
# 1.3.1 Sep 10, 2019
## 1.3.1 Sep 10, 2019
- Remove the `ExtError` class, always prefer the standard JS `Error` object for errors. This would bre a breaking change for any applications using `ExtError`
# 1.2.1 Sep 09, 2019
## 1.2.1 Sep 09, 2019
- Keyring `addFromAddress` can now be used to store external accounts, for example those provided by external signers
- Maintainability updates
# 1.1.1 Aug 09, 2019
## 1.1.1 Aug 09, 2019
- `assertSingletonPackage` now warns via console.warn, but does not throw. This does allow the info to come accross while still allowing the app developers using multiple libraries time to fix.
# 1.0.1 Aug 02, 2019
## 1.0.1 Aug 02, 2019
- `formatBalance` now allows for `Compact` inputs
- `formaBalance` now allows correct formatting of very large decimals
# 0.94.1 Jul 20, 2019
### 0.94.1 Jul 20, 2019
- Add `checkAddress(address, prefix)` to `@polkadot/util-crypto` that validates an ss-58 address
- Add support for the Kusama network (as a valid checked prefix)
@@ -116,7 +148,7 @@
- The ed25519 key for Alice (representing the session), now appears in the test keyrings
- Fix missing dependencies for keyring (after address moves in 0.93.1)
# 0.93.1 Jun 14, 2019
### 0.93.1 Jun 14, 2019
- Breaking: External pair interface for keyring has been changed. Instead of
- `getMeta` use the `meta` getter, i.e. `console.log(pair.meta.name)`
@@ -124,133 +156,133 @@
- `publicKey` use the `publicKey` getter, i.e. `console.log(pair.publicKey)`
- `Move decodeAddress`, `encodeAddress` & `setAddressPrefix` functions into `@polkadot/util-crypto` from `@polkadot/keyring`. External interfaces should not be affected at this point since it is also (still) exported and exposed on keyring
# 0.92.1 Jun 04, 2019
### 0.92.1 Jun 04, 2019
- Only allow integer input values into `formatBalance`
- Allow `formatBalance`, `formatDecimal` & `formatNumber` to cater for negative numbers
- Add 'Bob//stash' to testing keyring, joining the existing 'Alice//stash'
# 0.91.1 May 22, 2019
### 0.91.1 May 22, 2019
- ed25519/sr25519 sign & verify functions can now take the message input as Uint8Array/string/hex and verify allows for the signature/publicKey to be specified as Uint8Array/hex
- Update `@polkadot/wasm` to include a maintenance bump for the `w3f/schnorrkel` libraries
# 0.90.1 May 08, 2019
### 0.90.1 May 08, 2019
- Moving towards 1.0
- Added bnMin & bnMax functions
# 0.76.1 Apr 03, 2019
### 0.76.1 Apr 03, 2019
- Fix `addFromMnemonic` to generate using new-style derivation.
- Pull in `formatBalance`, `formatDecimal`, `formatElapsed`, `formatNumber`, `calcSi`, `findSi` & `isTestChain` utility functions from the originals in `@polkadot/ui-util`
- Swap out `wasm-schnorrkel` & `wasm-ed25519` for combined version with `wasm-crypto`
- Swap DB interfaces to optional LRU, removing `transactionAsync` (client-only changes)
# 0.75.1 Mar 29, 2019
### 0.75.1 Mar 29, 2019
- Start journey to 1.0
# 0.42.1 Mar 28, 2019
### 0.42.1 Mar 28, 2019
- Add `assertSingletonPackage` to util
- Ensure that only a single keyring instance is loaded (uses above)
# 0.41.1 Mar 25, 2019
### 0.41.1 Mar 25, 2019
- Extensions to the client-specific database interfaces (non-breaking for API and util users)
# 0.40.1 Mar 23, 2019
### 0.40.1 Mar 23, 2019
- Add additional derivation path extraction mechanisms to util-crypto
- Add createFromUri function to keypair (creates keypair, does not add it)
- Allow all crypto hashing & ed25519 to use WASM (as available, JS fallbacks)
# 0.39.1 Mar 20, 2019
### 0.39.1 Mar 20, 2019
- Pull in bip39 generation functions from `@poladkot/wasm-crypto` with a fallback to the pure JS versions
# 0.38.1 Mar 18, 2019
### 0.38.1 Mar 18, 2019
- Align with current substrate master for sr25519 keys and hard/soft derivation
- Swap default dev keys to derived (sr25519)
# 0.37.1 Mar 14, 2019
### 0.37.1 Mar 14, 2019
- Swap to publishing -beta.x on merge (non-breaking testing)
# 0.36.1 Mar 13, 2019
### 0.36.1 Mar 13, 2019
- Add `fromUri` to keyring along with hard & soft key derivation.
# 0.35.1 Mar 04, 2019
### 0.35.1 Mar 04, 2019
- Remove NodeJs-only `syncify` function, not exported by the package (with binary dependency for Node)
# 0.34.1 Feb 13, 2019
### 0.34.1 Feb 13, 2019
- Keyring now allows for ed25519 and sr25519 instances. Upon creation, you need to pass the `ed25519`or `sr25519` string to denote the type, i.e. `new Keyring({ type: 'sr25519' })`
# 0.33.1 Nov 22, 2018
### 0.33.1 Nov 22, 2018
# 0.32.1 Oct 18, 2018
### 0.32.1 Oct 18, 2018
# 0.31.1 Oct 12, 2018
### 0.31.1 Oct 12, 2018
# 0.30.1 Sep 11, 2018
### 0.30.1 Sep 11, 2018
# 0.29.1 Sep 01, 2018
### 0.29.1 Sep 01, 2018
# 0.28.1 Aug 11, 2018
### 0.28.1 Aug 11, 2018
# 0.27.1 Aug 06, 2018
### 0.27.1 Aug 06, 2018
# 0.26.1 Jun 27, 2018
### 0.26.1 Jun 27, 2018
# 0.25.1 Jun 26, 2018
### 0.25.1 Jun 26, 2018
# 0.24.1 Jun 22, 2018
### 0.24.1 Jun 22, 2018
# 0.23.1 Jun 21, 2018
### 0.23.1 Jun 21, 2018
# 0.22.1 May 24, 2018
### 0.22.1 May 24, 2018
# 0.21.1 May 17, 2018
### 0.21.1 May 17, 2018
# 0.20.1 May 16, 2018
### 0.20.1 May 16, 2018
# 0.19.1 Apr 19, 2018
### 0.19.1 Apr 19, 2018
# 0.18.1 Mar 20, 2018
### 0.18.1 Mar 20, 2018
# 0.17.1 Mar0 8, 2018
### 0.17.1 Mar0 8, 2018
# 0.16.1 Feb 23, 2018
### 0.16.1 Feb 23, 2018
# 0.15.1 Feb 15, 2018
### 0.15.1 Feb 15, 2018
# 0.14.1 Feb 07, 2018
### 0.14.1 Feb 07, 2018
# 0.13.1 Jan 25, 2018
### 0.13.1 Jan 25, 2018
# 0.12.1 Jan 11, 2018
### 0.12.1 Jan 11, 2018
# 0.11.1 Dec 30, 2017
### 0.11.1 Dec 30, 2017
# 0.10.1 Dec 17, 2017
### 0.10.1 Dec 17, 2017
# 0.9.1 Dec 14, 2017
### 0.9.1 Dec 14, 2017
# 0.8.1 Dec 12, 2017
### 0.8.1 Dec 12, 2017
# 0.7.1 Dec 11, 2017
### 0.7.1 Dec 11, 2017
# 0.6.1 Nov 30, 2017
### 0.6.1 Nov 30, 2017
# 0.5.1 Nov 20, 2017
### 0.5.1 Nov 20, 2017
# 0.4.1 Nov 19, 2017
### 0.4.1 Nov 19, 2017
# 0.3.1 Nov 19, 2017
### 0.3.1 Nov 19, 2017
# 0.2.1 Nov 18, 2017
### 0.2.1 Nov 18, 2017
+1 -1
View File
@@ -9,5 +9,5 @@
"packages": [
"packages/*"
],
"version": "2.9.1"
"version": "2.13.1"
}
+7 -6
View File
@@ -7,7 +7,7 @@
"packages/*"
],
"resolutions": {
"typescript": "^3.8.3"
"babel-core": "^7.0.0-bridge.0"
},
"scripts": {
"build": "polkadot-dev-build-ts",
@@ -21,9 +21,10 @@
"test:one": "polkadot-dev-run-test"
},
"devDependencies": {
"@babel/core": "^7.9.0",
"@polkadot/dev": "^0.52.11",
"@polkadot/ts": "^0.3.18",
"@types/jest": "^25.2.1"
}
"@babel/core": "^7.10.2",
"@polkadot/dev": "^0.55.8",
"@polkadot/ts": "^0.3.26",
"@types/jest": "^25.2.3"
},
"version": "2.13.1"
}
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/keyring",
"version": "2.9.1",
"version": "2.13.1",
"description": "Keyring management",
"main": "index.js",
"publishConfig": {
@@ -27,8 +27,8 @@
},
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/keyring#readme",
"dependencies": {
"@babel/runtime": "^7.9.2",
"@polkadot/util": "2.9.1",
"@polkadot/util-crypto": "2.9.1"
"@babel/runtime": "^7.10.2",
"@polkadot/util": "2.13.1",
"@polkadot/util-crypto": "2.13.1"
}
}
+3 -2
View File
@@ -7,9 +7,10 @@ import { KeyringPair$Json, KeyringPair$Meta } from '../types';
import { u8aToHex } from '@polkadot/util';
type PairStateJson = KeyringPair$Meta & {
interface PairStateJson {
address: string;
};
meta: KeyringPair$Meta;
}
export default function toJson (type: KeypairType, { address, meta }: PairStateJson, encoded: Uint8Array, isEncrypted: boolean): KeyringPair$Json {
return {
+1 -4
View File
@@ -10,10 +10,7 @@ export interface KeyringOptions {
type?: KeypairType;
}
export interface KeyringPair$Meta {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[index: string]: any;
}
export type KeyringPair$Meta = Record<string, unknown>;
export type KeyringPair$JsonVersion = '0' | '1' | '2';
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/util-crypto",
"version": "2.9.1",
"version": "2.13.1",
"description": "A collection of useful crypto utilities for @polkadot",
"main": "index.js",
"keywords": [
@@ -25,17 +25,17 @@
},
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util-crypto#readme",
"dependencies": {
"@babel/runtime": "^7.9.2",
"@polkadot/util": "2.9.1",
"@babel/runtime": "^7.10.2",
"@polkadot/util": "2.13.1",
"@polkadot/wasm-crypto": "^1.2.1",
"base-x": "^3.0.8",
"bip39": "^3.0.2",
"blakejs": "^1.1.0",
"bn.js": "^5.1.1",
"bn.js": "^5.1.2",
"bs58": "^4.0.1",
"elliptic": "^6.5.2",
"js-sha3": "^0.8.0",
"pbkdf2": "^3.0.17",
"pbkdf2": "^3.1.1",
"tweetnacl": "^1.0.3",
"xxhashjs": "^0.2.2"
},
@@ -44,6 +44,6 @@
"@types/bs58": "^4.0.1",
"@types/elliptic": "^6.4.12",
"@types/pbkdf2": "^3.0.0",
"@types/xxhashjs": "^0.2.1"
"@types/xxhashjs": "^0.2.2"
}
}
+1 -2
View File
@@ -19,8 +19,7 @@ export default function decode (encoded: string | Uint8Array, ignoreChecksum?: b
}
const decoded = bufferToU8a(bs58.decode(encoded));
const error = (message: string): string =>
`Decoding ${encoded}: ${message}`;
const error = (message: string) => `Decoding ${encoded as string}: ${message}`;
// assert(defaults.allowedPrefix.includes(decoded[0] as Prefix), error('Invalid decoded address prefix'));
assert(defaults.allowedEncodedLengths.includes(decoded.length), error('Invalid decoded address length'));
@@ -2,7 +2,8 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import testingPairs from '../../../keyring/src/testingPairs';
import testingPairs from '@polkadot/keyring/testingPairs';
import encode from './encode';
const keyring = testingPairs({ type: 'ed25519' }, false);
+1 -2
View File
@@ -17,10 +17,9 @@ export default function encode (_key: Uint8Array | string, ss58Format: Prefix =
// decode it, this means we can re-encode an address
const key = decode(_key);
assert(defaults.allowedDecodedLengths.includes(key.length), `Expected a valid key to convert, with length ${defaults.allowedDecodedLengths}`);
assert(defaults.allowedDecodedLengths.includes(key.length), `Expected a valid key to convert, with length ${defaults.allowedDecodedLengths.join(', ')}`);
const isPublicKey = key.length === 32;
const input = u8aConcat(new Uint8Array([ss58Format]), key);
const hash = sshash(input);
@@ -0,0 +1,46 @@
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import testingPairs from '@polkadot/keyring/testingPairs';
import { addressEq } from '.';
describe('addressEq', (): void => {
it('returns false with non-equal', (): void => {
expect(
addressEq(
'5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
'5EnxxUmEbw8DkENKiYuZ1DwQuMoB2UWEQJZZXrTsxoz7SpgG'
)
).toEqual(false);
});
it('returns true for equal, matching prefix', (): void => {
expect(
addressEq(
'5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
'5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'
)
).toEqual(true);
});
it('returns true for equal, non-matching prefix', (): void => {
expect(
addressEq(
'5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
'7sL6eNJj5ZGV5cn3hhV2deRUsivXfBfMH76wCALCqWj1EKzv'
)
).toEqual(true);
});
it('returns true for equal, address vs publicKey', (): void => {
const keyring = testingPairs({ type: 'sr25519' });
expect(
addressEq(
'5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
keyring.alice.publicKey
)
).toEqual(true);
});
});
+25
View File
@@ -0,0 +1,25 @@
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { u8aEq } from '@polkadot/util';
import decode from './decode';
/**
* @name addressEq
* @summary Compares two addresses, either in ss58, Uint8Array or hex format.
* @description
* For the input values, return true is the underlying public keys do match.
* @example
* <BR>
*
* ```javascript
* import { u8aEq } from '@polkadot/util';
*
* u8aEq(new Uint8Array([0x68, 0x65]), new Uint8Array([0x68, 0x65])); // true
* ```
*/
export default function addressEq (a: string | Uint8Array, b: string | Uint8Array): boolean {
return u8aEq(decode(a), decode(b));
}
@@ -8,10 +8,12 @@ import createKeyMulti from './keyMulti';
import createKeySub from './keySub';
import decodeAddress from './decode';
import encodeAddress from './encode';
import addressEq from './eq';
import setSS58Format from './setSS58Format';
import sortAddresses from './sort';
export {
addressEq,
checkAddress,
checkAddressChecksum,
createKeyMulti,
+4 -2
View File
@@ -3,15 +3,17 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import BN from 'bn.js';
import { bnToU8a, compactToU8a, u8aConcat, u8aSorted } from '@polkadot/util';
import { bnToU8a, compactToU8a, stringToU8a, u8aConcat, u8aSorted } from '@polkadot/util';
import blake2AsU8a from '../blake2/asU8a';
import decodeAddress from './decode';
const PREFIX = stringToU8a('modlpy/utilisuba');
export default function createKeyMulti (who: (Uint8Array | string)[], threshold: BigInt | BN | number): Uint8Array {
return blake2AsU8a(
u8aConcat(
'modlpy/utilisuba',
PREFIX,
compactToU8a(who.length),
...u8aSorted(who.map((who) => decodeAddress(who))),
bnToU8a(threshold, { bitLength: 16, isLe: true })
+4 -2
View File
@@ -3,15 +3,17 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import BN from 'bn.js';
import { bnToU8a, u8aConcat } from '@polkadot/util';
import { bnToU8a, stringToU8a, u8aConcat } from '@polkadot/util';
import blake2AsU8a from '../blake2/asU8a';
import decodeAddress from './decode';
const PREFIX = stringToU8a('modlpy/utilisuba');
export default function createKeySub (who: Uint8Array | string, index: BigInt | BN | number): Uint8Array {
return blake2AsU8a(
u8aConcat(
'modlpy/utilisuba',
PREFIX,
decodeAddress(who),
bnToU8a(index, { bitLength: 16, isLe: true })
)
+2
View File
@@ -7,6 +7,8 @@ export const allowedSS58 = [
0, 1,
// Kusama
2, 3,
// Kulupu
16, 17,
// Dothereum
20,
// Substrate default
@@ -43,4 +43,18 @@ describe('blake2AsU8a', (): void => {
hexToU8a('0xba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923')
);
});
it('has equivalent Wasm/Js outputs on hex inputs', (): void => {
const a = blake2AsU8a('0x123456', 256, null, false);
const b = blake2AsU8a('0x123456', 256, null, true);
expect(a).toEqual(b);
});
it('has equivalent Wasm/Js outputs with key inputs', (): void => {
const a = blake2AsU8a('0x123456', 256, new Uint8Array([1, 2]), false);
const b = blake2AsU8a('0x123456', 256, new Uint8Array([1, 2]), true);
expect(a).toEqual(b);
});
});
+3 -3
View File
@@ -20,10 +20,10 @@ import { blake2b, isReady } from '@polkadot/wasm-crypto';
* blake2AsU8a('abc'); // => [0xba, 0x80, 0xa53, 0xf98, 0x1c, 0x4d, 0x0d]
* ```
*/
export default function blake2AsU8a (data: Uint8Array | string, bitLength = 256, key: Uint8Array | null = null): Uint8Array {
export default function blake2AsU8a (data: Uint8Array | string, bitLength = 256, key: Uint8Array | null = null, onlyJs = false): Uint8Array {
const byteLength = Math.ceil(bitLength / 8);
return isReady()
return isReady() && !onlyJs
? blake2b(u8aToU8a(data), u8aToU8a(key), byteLength)
: blakejs.blake2b(data, key, byteLength);
: blakejs.blake2b(u8aToU8a(data), key, byteLength);
}
@@ -2,8 +2,9 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import BN from 'bn.js';
import { bnToHex, compactAddLength, hexToU8a, isBn, isHex, isNumber, isString, stringToU8a } from '@polkadot/util';
import type BN from 'bn.js';
import { bnToHex, compactAddLength, hexToU8a, isBigInt, isBn, isHex, isNumber, isString, stringToU8a } from '@polkadot/util';
import blake2AsU8a from '../blake2/asU8a';
@@ -21,10 +22,10 @@ export default class DeriveJunction {
#isHard = false;
public static from (value: string): DeriveJunction {
const result = new DeriveJunction();
const [code, isHard] = value.startsWith('/')
? [value.substr(1), true]
: [value, false];
const result = new DeriveJunction();
result.soft(
RE_NUMBER.test(code)
@@ -49,7 +50,7 @@ export default class DeriveJunction {
return !this.#isHard;
}
public hard (value: number | BN | string | Uint8Array): DeriveJunction {
public hard (value: number | string | BigInt | BN | Uint8Array): DeriveJunction {
return this.soft(value).harden();
}
@@ -59,8 +60,8 @@ export default class DeriveJunction {
return this;
}
public soft (value: number | BN | string | Uint8Array): DeriveJunction {
if (isNumber(value) || isBn(value)) {
public soft (value: number | string | BigInt | BN | Uint8Array): DeriveJunction {
if (isNumber(value) || isBn(value) || isBigInt(value)) {
return this.soft(bnToHex(value, BN_OPTIONS));
} else if (isString(value)) {
return isHex(value)
+1 -1
View File
@@ -13,7 +13,7 @@ export interface ExtractResult {
}
/**
* @description Extract derivation juntions from the supplied path
* @description Extract derivation junctions from the supplied path
*/
export default function keyExtractPath (derivePath: string): ExtractResult {
const parts = derivePath.match(RE_JUNCTION);
+7 -5
View File
@@ -9,12 +9,14 @@ import keyHdkdEd15519 from './hdkdEd25519';
import keyHdkdSr15519 from './hdkdSr25519';
import keyHdkdEcdsa from './hdkdEcdsa';
const generators = {
ecdsa: keyHdkdEcdsa,
ed25519: keyHdkdEd15519,
sr25519: keyHdkdSr15519
};
export default function keyFromPath (pair: Keypair, path: DeriveJunction[], type: KeypairType): Keypair {
const keyHdkd = {
ecdsa: keyHdkdEcdsa,
ed25519: keyHdkdEd15519,
sr25519: keyHdkdSr15519
}[type];
const keyHdkd = generators[type];
return path.reduce((pair, junction): Keypair => {
return keyHdkd(pair, junction);
@@ -11,5 +11,4 @@ import '../polyfill';
export { default as mnemonicGenerate } from './generate';
export { default as mnemonicToEntropy } from './toEntropy';
export { default as mnemonicToMiniSecret } from './toMiniSecret';
export { default as mnemonicToSeed } from './toSeed';
export { default as mnemonicValidate } from './validate';
@@ -1,15 +0,0 @@
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { u8aToHex } from '@polkadot/util';
import toSeed from './toSeed';
describe('mnemonicToSeed', (): void => {
it('generates a valid seed', (): void => {
expect(
u8aToHex(toSeed('seed sock milk update focus rotate barely fade car face mechanic mercy'))
).toEqual('0x3c121e20de068083b49c2315697fb59a2d9e8643c24e5ea7628132c58969a027');
});
});
@@ -1,30 +0,0 @@
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { mnemonicToSeedSync } from 'bip39';
import { bufferToU8a } from '@polkadot/util';
import { bip39ToSeed, isReady } from '@polkadot/wasm-crypto';
/**
* @name toSeed
* @summary Creates a valid seed from a mnemonic input
* @example
* <BR>
*
* ```javascript
* import { mnemonicGenerate, mnemonicToSeed, mnemonicValidate } from '@polkadot/util-crypto';
*
* const mnemonic = mnemonicGenerate(); // => string
* const isValidMnemonic = mnemonicValidate(mnemonic); // => boolean
*
* if (isValidMnemonic) {
* console.log(`Seed generated from mnemonic: ${mnemonicToSeed(mnemonic)}`); => u8a
* }
* ```
*/
export default function toSeed (mnemonic: string, password = ''): Uint8Array {
return isReady()
? bip39ToSeed(mnemonic, password)
: bufferToU8a(mnemonicToSeedSync(mnemonic, password)).subarray(0, 32);
}
+9 -9
View File
@@ -33,19 +33,19 @@ describe('naclOpen', (): void => {
// Receiver sends encrypting public key to receive message to decrypt with his private key
const receiverIdBoxKey = naclBoxKeypairFromSecret(receiverIdKey.secretKey);
console.log(`Receiver sends receiver's public key to sender ${receiverIdBoxKey.publicKey}`);
console.log(`Receiver sends receiver's public key to sender ${receiverIdBoxKey.publicKey.toString()}`);
// Sender encrypts message to send with the public key the receiver sent and send it to receiver
const senderIdBoxKey = naclBoxKeypairFromSecret(senderIdKey.secretKey);
const message = new Uint8Array([1, 2, 3, 4, 5, 4, 3, 2, 1]);
const { nonce, sealed } = naclSeal(message, senderIdBoxKey.secretKey, receiverIdBoxKey.publicKey);
console.log(`Sender sends encrypted message to receiver ${sealed}, ${nonce}`);
console.log(`Sender sends encrypted message to receiver ${sealed.toString()}, ${nonce.toString()}`);
// Receiver opens encrypted message from the sender
let opened = naclOpen(sealed, nonce, senderIdBoxKey.publicKey, receiverIdBoxKey.secretKey);
console.log(`The sealed message is ${opened}`);
console.log(`The sealed message is ${opened?.toString() || 'null'}`);
// Oh no the Id key is hacked, derive Id key again from another index
const senderIdKey2 = fromPath(sender, keyExtractPath('//1//1//1//2').path, 'ed25519');
@@ -54,7 +54,7 @@ describe('naclOpen', (): void => {
// Receiver sends encrypting public key to receive message to decrypt with his private key
const receiverIdBoxKey2 = naclBoxKeypairFromSecret(receiverIdKey2.secretKey);
console.log(`Receiver sends receiver's public key to sender ${receiverIdBoxKey2.publicKey}`);
console.log(`Receiver sends receiver's public key to sender ${receiverIdBoxKey2.publicKey.toString()}`);
// Sender encrypts message to send with the public key the receiver sent and send it to receiver
const senderIdBoxKey2 = naclBoxKeypairFromSecret(senderIdKey2.secretKey);
@@ -63,17 +63,17 @@ describe('naclOpen', (): void => {
const sealed2 = ctx.sealed;
const nonce2 = ctx.nonce;
console.log(`Sender sends encrypted message to receiver ${sealed}, ${nonce}`);
console.log(`Sender sends encrypted message to receiver ${sealed.toString()}, ${nonce.toString()}`);
// Receiver opens encrypted message from the sender
opened = naclOpen(sealed2, nonce2, senderIdBoxKey2.publicKey, receiverIdBoxKey2.secretKey);
console.log(`The sealed message is ${opened}`);
console.log(`The sealed message is ${opened?.toString() || 'null'}`);
// This time derive key for each message to send and receive
// Receiver sends encrypting public key to receive message to decrypt with his private key
const receiverIdBoxKey2One = naclBoxKeypairFromSecret(receiverIdBoxKey2.secretKey);
console.log(`Receiver sends receiver's public key to sender ${receiverIdBoxKey2One.publicKey}`);
console.log(`Receiver sends receiver's public key to sender ${receiverIdBoxKey2One.publicKey.toString()}`);
// Sender encrypts message to send with the public key the receiver sent and send it to receiver
const senderIdBoxKey2One = naclBoxKeypairFromSecret(senderIdBoxKey2.secretKey);
@@ -84,11 +84,11 @@ describe('naclOpen', (): void => {
const sealed3 = ctx.sealed;
const nonce3 = ctx.nonce;
console.log(`Sender sends encrypted message to receiver ${sealed3}, ${nonce3}`);
console.log(`Sender sends encrypted message to receiver ${sealed3.toString()}, ${nonce3.toString()}`);
// Receiver opens encrypted message from the sender
opened = naclOpen(sealed2, nonce2, senderIdBoxKey2One.publicKey, receiverIdBoxKey2One.secretKey);
console.log(`The sealed message is ${opened}`);
console.log(`The sealed message is ${opened?.toString() || 'null'}`);
});
it('returns null on invalid', (): void => {
+1 -1
View File
@@ -23,7 +23,7 @@ import { isReady, ed25519Sign } from '@polkadot/wasm-crypto';
* ```
*/
export default function naclSign (message: Uint8Array | string, { publicKey, secretKey }: Partial<Keypair>): Uint8Array {
assert(secretKey, 'Expected valid secretKey');
assert(secretKey, 'Expected a valid secretKey');
const messageU8a = u8aToU8a(message);
+21 -1
View File
@@ -7,7 +7,7 @@ import { waitReady } from '@polkadot/wasm-crypto';
import { naclVerify, naclKeypairFromSeed } from '.';
describe('naclSign', (): void => {
describe('naclVerify', (): void => {
let publicKey: Uint8Array;
let signature: Uint8Array;
@@ -51,4 +51,24 @@ describe('naclSign', (): void => {
)
).toEqual(false);
});
it('throws error when publicKey lengths do not match', (): void => {
expect(
() => naclVerify(
new Uint8Array([0x61, 0x62, 0x63, 0x64]),
signature,
new Uint8Array([1, 2])
)
).toThrow(/Invalid publicKey/);
});
it('throws error when signature lengths do not match', (): void => {
expect(
() => naclVerify(
new Uint8Array([0x61, 0x62, 0x63, 0x64]),
new Uint8Array([1, 2]),
publicKey
)
).toThrow(/Invalid signature/);
});
});
+6 -3
View File
@@ -3,14 +3,14 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import nacl from 'tweetnacl';
import { u8aToU8a } from '@polkadot/util';
import { assert, u8aToU8a } from '@polkadot/util';
import { isReady, ed25519Verify } from '@polkadot/wasm-crypto';
/**
* @name naclSign
* @summary Verifies the signature on the supplied message.
* @description
* Verifies the `signature` on `message` with the supplied `plublicKey`. Returns `true` on sucess, `false` otherwise.
* Verifies the `signature` on `message` with the supplied `publicKey`. Returns `true` on sucess, `false` otherwise.
* @example
* <BR>
*
@@ -22,8 +22,11 @@ import { isReady, ed25519Verify } from '@polkadot/wasm-crypto';
*/
export default function naclVerify (message: Uint8Array | string, signature: Uint8Array | string, publicKey: Uint8Array | string): boolean {
const messageU8a = u8aToU8a(message);
const signatureU8a = u8aToU8a(signature);
const publicKeyU8a = u8aToU8a(publicKey);
const signatureU8a = u8aToU8a(signature);
assert(publicKeyU8a.length === 32, `Invalid publicKey, received ${publicKeyU8a.length}, expected 32`);
assert(signatureU8a.length === 64, `Invalid signature, received ${signatureU8a.length} bytes, expected 64`);
return isReady()
? ed25519Verify(signatureU8a, messageU8a, publicKeyU8a)
+2 -2
View File
@@ -14,8 +14,8 @@ import { sr25519Sign } from '@polkadot/wasm-crypto';
* @description Returns message signature of `message`, using the supplied pair
*/
export default function schnorrkelSign (message: Uint8Array | string, { publicKey, secretKey }: Partial<Keypair>): Uint8Array {
assert(publicKey?.length === 32, 'Expected valid publicKey, 32-bytes');
assert(secretKey?.length === 64, 'Expected valid secretKey, 64-bytes');
assert(publicKey?.length === 32, 'Expected a valid publicKey, 32-bytes');
assert(secretKey?.length === 64, 'Expected a valid secretKey, 64-bytes');
const messageU8a = u8aToU8a(message);
@@ -29,4 +29,24 @@ describe('sign and verify', (): void => {
expect(verify(MESSAGE, signature, pair.publicKey)).toBe(true);
});
it('throws error when publicKey lengths do not match', (): void => {
expect(
() => verify(
new Uint8Array([0x61, 0x62, 0x63, 0x64]),
new Uint8Array(64),
new Uint8Array(31)
)
).toThrow(/Invalid publicKey/);
});
it('throws error when signature lengths do not match', (): void => {
expect(
() => verify(
new Uint8Array([0x61, 0x62, 0x63, 0x64]),
new Uint8Array(65),
new Uint8Array(32)
)
).toThrow(/Invalid signature/);
});
});
@@ -4,7 +4,7 @@
import '../polyfill';
import { u8aToU8a } from '@polkadot/util';
import { assert, u8aToU8a } from '@polkadot/util';
import { sr25519Verify } from '@polkadot/wasm-crypto';
/**
@@ -13,8 +13,11 @@ import { sr25519Verify } from '@polkadot/wasm-crypto';
*/
export default function schnorrkelVerify (message: Uint8Array | string, signature: Uint8Array | string, publicKey: Uint8Array | string): boolean {
const messageU8a = u8aToU8a(message);
const signatureU8a = u8aToU8a(signature);
const publicKeyU8a = u8aToU8a(publicKey);
const signatureU8a = u8aToU8a(signature);
assert(publicKeyU8a.length === 32, `Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
assert(signatureU8a.length === 64, `Invalid signature, received ${signatureU8a.length} bytes, expected 64`);
return sr25519Verify(signatureU8a, messageU8a, publicKeyU8a);
}
@@ -14,11 +14,12 @@ const ec = new EC('secp256k1');
* @description Returns a object containing a `publicKey` & `secretKey` generated from the supplied seed.
*/
export default function secp256k1KeypairFromSeed (seed: Uint8Array): Keypair {
assert(seed.length === 32, 'Expected valid 32-byte private key as a seed: ' + seed);
assert(seed.length === 32, 'Expected valid 32-byte private key as a seed');
const key = ec.keyFromPrivate(seed);
return {
publicKey: new Uint8Array(key.getPublic().encodeCompressed('array')),
secretKey: hexToU8a('0x' + key.getPrivate('hex'))
secretKey: hexToU8a(`0x${key.getPrivate('hex')}`)
};
}
@@ -13,6 +13,7 @@ const ec = new EC('secp256k1');
*/
export default function secp256k1Recover (message: Uint8Array, signature: Uint8Array, recovery: number): Uint8Array {
return new Uint8Array(
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
ec
.recoverPubKey(message, { r: signature.slice(0, 32), s: signature.slice(32, 64) }, recovery)
.encode(null, true)
@@ -21,6 +21,7 @@ export default function secp256k1Verify (message: Uint8Array | string, signature
};
const recovery = signatureU8a[64];
const publicKey = new Uint8Array(
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
ec.recoverPubKey(blake2AsU8a(message, 256), sig, recovery)
.encodeCompressed(null)
);
+2 -3
View File
@@ -67,10 +67,9 @@ export default function signatureVerify (message: Uint8Array | string, signature
const result: VerifyResult = { crypto: 'none', isValid: false };
const publicKey = addressDecode(addressOrPublicKey);
const isMultisig = [0, 1, 2].includes(signatureU8a[0]) && [65, 66].includes(signatureU8a.length);
const multisig = [0, 1, 2].includes(signatureU8a[0]) && [65, 66].includes(signatureU8a.length);
if (multisig) {
if (isMultisig) {
return verifyMultisig(result, message, signatureU8a, publicKey);
} else {
return verifyDetect(result, message, signatureU8a, publicKey);
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/util",
"version": "2.9.1",
"version": "2.13.1",
"description": "A collection of useful utilities for @polkadot",
"main": "index.js",
"keywords": [
@@ -25,9 +25,9 @@
},
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util#readme",
"dependencies": {
"@babel/runtime": "^7.9.2",
"@babel/runtime": "^7.10.2",
"@types/bn.js": "^4.11.6",
"bn.js": "^5.1.1",
"bn.js": "^5.1.2",
"camelcase": "^5.3.1",
"chalk": "^4.0.0",
"ip-regex": "^4.1.0"
+4 -4
View File
@@ -21,8 +21,8 @@ import isUndefined from '../is/undefined';
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function arrayFilter (array: any[], allowNulls = true): any[] {
return array.filter((value): boolean => {
return !isUndefined(value) && (allowNulls || !isNull(value));
});
export default function arrayFilter <T = any> (array: T[], allowNulls = true): T[] {
return array.filter((value) =>
!isUndefined(value) && (allowNulls || !isNull(value))
);
}
+1 -1
View File
@@ -22,7 +22,7 @@ type MessageFn = () => string;
* assert(false, () => 'message'); // Error with 'message'
* ```
*/
export default function assert (condition: boolean | object | string | number | undefined | null, message: string | MessageFn): asserts condition {
export default function assert (condition: unknown, message: string | MessageFn): asserts condition {
if (!condition) {
throw new Error(
isFunction(message)
+1 -1
View File
@@ -22,5 +22,5 @@ import assert from '../assert';
export default function max (...items: BN[]): BN {
assert(items && items.length >= 1, 'Must provide one or more BN arguments');
return items.reduce((acc: BN, val: BN): BN => BN.max(acc, val), items[0]);
return items.reduce((acc: BN, val: BN) => BN.max(acc, val), items[0]);
}
+1 -1
View File
@@ -22,5 +22,5 @@ import assert from '../assert';
export default function min (...items: BN[]): BN {
assert(items && items.length >= 1, 'Must provide one or more BN arguments');
return items.reduce((acc: BN, val: BN): BN => BN.min(acc, val), items[0]);
return items.reduce((acc: BN, val: BN) => BN.min(acc, val), items[0]);
}
+1 -1
View File
@@ -21,7 +21,7 @@ describe('bnToBn', (): void => {
it('converts BigInt values to BN', (): void => {
expect(
bnToBn(128_821n).toNumber()
bnToBn(128821n).toNumber()
).toEqual(128821);
});
+6
View File
@@ -25,6 +25,12 @@ describe('bnToHex', (): void => {
).toBe('0x0080');
});
it('converts BN values to a prefixed hex representation (bitLength + le)', (): void => {
expect(
bnToHex(new BN(128), 16, true)
).toBe('0x8000');
});
it('converts BN values to a prefixed hex representation (LE)', (): void => {
expect(
bnToHex(new BN(128), { bitLength: 16, isLe: true })
+8 -3
View File
@@ -2,11 +2,12 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ToBn, ToBnOptions } from '../types';
import BN from 'bn.js';
import isNumber from '../is/number';
import bnToU8a from './toU8a';
import { ToBnOptions } from '../types';
import { u8aToHex } from '../u8a';
const ZERO_STR = '0x00';
@@ -30,7 +31,9 @@ interface Options extends ToBnOptions {
* bnToHex(new BN(0x123456)); // => '0x123456'
* ```
*/
export default function bnToHex (value?: BN | BigInt | number | null, options: number | Options = { bitLength: -1, isLe: false, isNegative: false }): string {
function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null, options?: Options): string;
function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null, bitLength?: number, isLe?: boolean): string;
function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null, arg1: number | Options = { bitLength: -1, isLe: false, isNegative: false }, arg2?: boolean): string {
if (!value) {
return ZERO_STR;
}
@@ -39,8 +42,10 @@ export default function bnToHex (value?: BN | BigInt | number | null, options: n
isLe: false,
isNegative: false,
// Backwards-compatibility
...(isNumber(options) ? { bitLength: options } : options)
...(isNumber(arg1) ? { bitLength: arg1, isLe: arg2 } : arg1)
};
return u8aToHex(bnToU8a(value, _options));
}
export default bnToHex;
+1 -1
View File
@@ -10,7 +10,7 @@ describe('bnToU8a', (): void => {
it('converts null values to 0x00', (): void => {
expect(
bnToU8a(null, -1, false)
).toEqual(new Uint8Array([]));
).toEqual(new Uint8Array());
});
it('converts null values to 0x00000000 (bitLength)', (): void => {
+6 -5
View File
@@ -2,11 +2,12 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ToBn, ToBnOptions } from '../types';
import BN from 'bn.js';
import isNumber from '../is/number';
import bnToBn from './toBn';
import { ToBnOptions } from '../types';
interface Options extends ToBnOptions {
bitLength?: number;
@@ -26,9 +27,9 @@ interface Options extends ToBnOptions {
* bnToU8a(new BN(0x1234)); // => [0x12, 0x34]
* ```
*/
function bnToU8a (value: BN | BigInt | number | null, options?: Options): Uint8Array;
function bnToU8a (value: BN | BigInt | number | null, bitLength?: number, isLe?: boolean): Uint8Array;
function bnToU8a (value: BN | BigInt | number | null, arg1: number | Options = { bitLength: -1, isLe: true, isNegative: false }, arg2?: boolean): Uint8Array {
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null, options?: Options): Uint8Array;
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null, bitLength?: number, isLe?: boolean): Uint8Array;
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null, arg1: number | Options = { bitLength: -1, isLe: true, isNegative: false }, arg2?: boolean): Uint8Array {
const _options: Options = {
bitLength: -1,
isLe: true,
@@ -43,7 +44,7 @@ function bnToU8a (value: BN | BigInt | number | null, arg1: number | Options = {
if (!value) {
return _options.bitLength === -1
? new Uint8Array([])
? new Uint8Array()
: new Uint8Array(byteLength);
}
+1 -1
View File
@@ -8,7 +8,7 @@ describe('bufferToU8a', (): void => {
it('returns an empty buffer when null provided', (): void => {
expect(
bufferToU8a(null)
).toEqual(new Uint8Array([]));
).toEqual(new Uint8Array());
});
it('returns a Uint8Buffer with the correct values', (): void => {
+1 -5
View File
@@ -17,9 +17,5 @@
* ```
*/
export default function bufferToU8a (buffer?: Buffer | number[] | null): Uint8Array {
if (!buffer) {
return new Uint8Array([]);
}
return new Uint8Array(buffer);
return new Uint8Array(buffer || []);
}
+1 -1
View File
@@ -39,7 +39,7 @@ function flattenVersions (_all: (VersionPath | string)[]): string {
const verLength = all.reduce((max, { version }): number => Math.max(max, version.length), 0);
return all
.map(({ path, version }): string => `\t${version.padEnd(verLength)}\t${expandPath(path)}`)
.map(({ path, version }) => `\t${version.padEnd(verLength)}\t${expandPath(path)}`)
.join('\n');
}
@@ -23,7 +23,7 @@ describe('formatBalance', (): void => {
it('formats BigInt numbers', (): void => {
expect(
formatBalance(123_456_789_000n, { decimals: 15, withSi: true })
formatBalance(123456789000n, { decimals: 15, withSi: true })
).toEqual('123.456µ Unit');
});
@@ -27,7 +27,7 @@ describe('formatNumber', (): void => {
it('formats BigInt numbers', (): void => {
expect(
formatNumber(123_456_789n)
formatNumber(123456789n)
).toEqual('123,456,789');
});
+6
View File
@@ -53,6 +53,12 @@ describe('hexToBn', (): void => {
).toBe(-1234);
});
it('handles negative numbers (LE, 128)', (): void => {
expect(
hexToBn('0x00009c584c491ff2ffffffffffffffff', { isLe: true, isNegative: true }).toString()
).toEqual('-1000000000000000000');
});
it('handles starting zeros correctly (BE)', (): void => {
expect(
hexToBn('0x0000000000000100', { isLe: false }).toNumber()
+1 -1
View File
@@ -23,7 +23,7 @@ import hexStripPrefix from './stripPrefix';
*/
export default function hexToU8a (_value?: string | null, bitLength = -1): Uint8Array {
if (!_value) {
return new Uint8Array([]);
return new Uint8Array();
}
assert(isHex(_value), `Expected hex value to convert, found '${_value}'`);
+2 -2
View File
@@ -7,13 +7,13 @@ import { isBigInt } from '.';
describe('isBigInt', (): void => {
it('returns true when a BigInt value', (): void => {
expect(
isBigInt(123_456n)
isBigInt(123456n)
).toEqual(true);
});
it('returns true when a BigInt value', (): void => {
expect(
isBigInt(BigInt(123_456))
isBigInt(BigInt(123456))
).toEqual(true);
});
+1 -1
View File
@@ -16,6 +16,6 @@
* console.log('isBigInt', isBigInt(123_456n)); // => true
* ```
*/
export default function isBigInt (value: BigInt | object | string | number | undefined | null): value is BigInt {
export default function isBigInt (value: unknown): value is BigInt {
return typeof value === 'bigint';
}
+1 -1
View File
@@ -19,6 +19,6 @@ import BN from 'bn.js';
* console.log('isBn', isBn(new BN(1))); // => true
* ```
*/
export default function isBn (value: object | string | number | undefined | null): value is BN {
export default function isBn (value: unknown): value is BN {
return BN.isBN(value);
}
+1 -2
View File
@@ -16,7 +16,6 @@
* isBoolean(false); // => true
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function isBoolean (value: any): value is boolean {
export default function isBoolean (value: unknown): value is boolean {
return typeof value === 'boolean';
}
+1 -2
View File
@@ -18,7 +18,6 @@ import isInstanceOf from './instanceOf';
* console.log('isBuffer', isBuffer(Buffer.from([]))); // => true
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function isBuffer (value: any): value is Buffer {
export default function isBuffer (value: unknown): value is Buffer {
return isInstanceOf(value, Buffer);
}
+1 -2
View File
@@ -18,7 +18,6 @@ import isInstanceOf from './instanceOf';
* console.log('isError', isError(new Error('message'))); // => true
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function isError (value: any): value is Error {
export default function isError (value: unknown): value is Error {
return isInstanceOf(value, Error);
}
+4 -2
View File
@@ -2,6 +2,9 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
// eslint-disable-next-line @typescript-eslint/ban-types
type FnType = Function;
/**
* @name isFunction
* @summary Tests for a `function`.
@@ -16,7 +19,6 @@
* isFunction(() => false); // => true
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function isFunction (value: any): value is Function {
export default function isFunction (value: unknown): value is FnType {
return typeof value === 'function';
}
+4 -4
View File
@@ -21,13 +21,13 @@ const HEX_REGEX = /^0x[a-fA-F0-9]+$/;
* isHex('0x1234', 8); // => false
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/ban-types
export default function isHex (value: any, bitLength = -1, ignoreLength = false): value is string | String {
// eslint-disable-next-line @typescript-eslint/ban-types
export default function isHex (value: unknown, bitLength = -1, ignoreLength = false): value is string | String {
const isValidHex = value === '0x' || (isString(value) && HEX_REGEX.test(value.toString()));
if (isValidHex && bitLength !== -1) {
return value.length === (2 + Math.ceil(bitLength / 4));
return (value as string).length === (2 + Math.ceil(bitLength / 4));
}
return isValidHex && (ignoreLength || (value.length % 2 === 0));
return isValidHex && (ignoreLength || ((value as string).length % 2 === 0));
}
+2 -2
View File
@@ -16,7 +16,7 @@
* console.log('isInstanceOf', isInstanceOf(new Array(0), Array)); // => true
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function isInstanceOf (value: any, clazz: any): boolean {
// eslint-disable-next-line @typescript-eslint/ban-types
export default function isInstanceOf (value: unknown, clazz: Function): boolean {
return value instanceof clazz;
}
+4 -6
View File
@@ -31,17 +31,15 @@ interface ObjectIndexed {
* isJsonObject('not an object'); // => false
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function isJsonObject (value: any): value is ObjectIndexed {
value = typeof value !== 'string'
export default function isJsonObject (value: unknown): value is ObjectIndexed {
const str = typeof value !== 'string'
? JSON.stringify(value)
: value;
try {
value = JSON.parse(value);
const obj = JSON.parse(str) as unknown;
return (typeof value === 'object' && value !== null);
return (typeof obj === 'object' && obj !== null);
} catch (e) {
return false;
}
+1 -2
View File
@@ -16,7 +16,6 @@
* console.log('isNull', isNull(null)); // => true
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function isNull (value?: any): value is null {
export default function isNull (value?: unknown): value is null {
return value === null;
}
+1 -2
View File
@@ -16,7 +16,6 @@
* console.log('isNumber', isNumber(1234)); // => true
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function isNumber (value: any): value is number {
export default function isNumber (value: unknown): value is number {
return typeof value === 'number';
}
+1 -2
View File
@@ -22,7 +22,6 @@ interface ObjectIndexed {
* isObject('something'); // => false
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function isObject (value: any): value is ObjectIndexed {
export default function isObject (value: unknown): value is ObjectIndexed {
return typeof value === 'object';
}
+1 -2
View File
@@ -24,7 +24,6 @@ interface Observable {
* console.log('isObservable', isObservable(...));
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function isObservable (value: any): value is Observable {
export default function isObservable (value: unknown): value is Observable {
return isObject(value) && isFunction((value as Observable).next);
}
+2 -2
View File
@@ -16,7 +16,7 @@
* console.log('isString', isString('test')); // => true
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/ban-types
export default function isString (value: any): value is string | String {
// eslint-disable-next-line @typescript-eslint/ban-types
export default function isString (value: unknown): value is string | String {
return typeof value === 'string' || value instanceof String;
}
+1 -2
View File
@@ -6,7 +6,6 @@ import { ToBn } from '../types';
import isFunction from './function';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function isToBn (value?: any): value is ToBn {
export default function isToBn (value?: unknown): value is ToBn {
return !!value && isFunction((value as ToBn).toBn);
}
+1 -1
View File
@@ -19,7 +19,7 @@ describe('isUint8Array', (): void => {
it('returns true on Uint8Array values', (): void => {
expect(
isU8a(new Uint8Array([]))
isU8a(new Uint8Array())
).toEqual(true);
});
});
+1 -2
View File
@@ -18,7 +18,6 @@ import isInstanceOf from './instanceOf';
* console.log('isU8a', isU8a([])); // => false
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function isU8a (value?: any): value is Uint8Array {
export default function isU8a (value?: unknown): value is Uint8Array {
return isInstanceOf(value, Uint8Array);
}
+1 -1
View File
@@ -17,6 +17,6 @@
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function isUndefined (value?: any): value is undefined {
export default function isUndefined (value?: unknown): value is undefined {
return typeof value === 'undefined';
}
+5 -6
View File
@@ -8,10 +8,8 @@ import { logger } from '.';
import { format } from './logger';
describe('logger', (): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let dateMatch: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let prefixMatch: any;
let dateMatch: unknown;
let prefixMatch: unknown;
let l: Logger;
let ln: Logger;
let spy: Partial<Console>;
@@ -34,7 +32,9 @@ describe('logger', (): void => {
};
global.console = spy as Console;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
dateMatch = expect.stringMatching(/20[0-9]{2}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}/);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
prefixMatch = expect.stringMatching(/TEST:/);
});
@@ -146,8 +146,7 @@ describe('logger', (): void => {
});
it('does not debug log when no process.env', (): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
process.env = undefined as any;
process.env = undefined as unknown as NodeJS.ProcessEnv;
l = logger('test');
l.debug('test');
+6 -12
View File
@@ -31,22 +31,17 @@ const chalked = {
warn: chalk.yellow
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function formatObject (value: Record<string, any>): any {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result: Record<string, any> = {};
function formatObject (value: Record<string, unknown>): Record<string, unknown> {
const result: Record<string, unknown> = {};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return Object.keys(value).reduce((result, key): Record<string, any> => {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
return Object.keys(value).reduce((result, key): Record<string, unknown> => {
result[key] = format(value[key]);
return result;
}, result);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function format (value: any): any {
export function format (value: unknown): unknown {
if (Array.isArray(value)) {
return value.map(format);
}
@@ -72,7 +67,7 @@ export function format (value: any): any {
function apply (log: LogType, type: string, values: Logger$Data): void {
if (values.length === 1 && isFunction(values[0])) {
const fnResult = (values[0] as Function)();
const fnResult = values[0]() as unknown;
return apply(log, type, Array.isArray(fnResult) ? fnResult : [fnResult]);
}
@@ -87,8 +82,7 @@ function apply (log: LogType, type: string, values: Logger$Data): void {
);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function noop (...values: Logger$Data): void {
function noop (): void {
// noop
}
+4 -4
View File
@@ -8,25 +8,25 @@ describe('numberToU8a', (): void => {
it('converts 0 to empty', (): void => {
expect(
numberToU8a(0)
).toEqual(new Uint8Array([]));
).toEqual(new Uint8Array());
});
it('converts undefined to empty', (): void => {
expect(
numberToU8a()
).toEqual(new Uint8Array([]));
).toEqual(new Uint8Array());
});
it('converts null to empty', (): void => {
expect(
numberToU8a(null)
).toEqual(new Uint8Array([]));
).toEqual(new Uint8Array());
});
it('converts NaN to empty', (): void => {
expect(
numberToU8a(NaN)
).toEqual(new Uint8Array([]));
).toEqual(new Uint8Array());
});
it('converts values to the u8a', (): void => {
+1 -1
View File
@@ -21,7 +21,7 @@ import numberToHex from './toHex';
*/
export default function numberToU8a (value?: number | null, bitLength = -1): Uint8Array {
if (!value || isNaN(value)) {
return new Uint8Array([]);
return new Uint8Array();
}
return hexToU8a(
+2 -1
View File
@@ -2,7 +2,6 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
/* eslint-disable @typescript-eslint/ban-ts-ignore */
/* eslint-disable no-extend-native */
/* eslint-disable @typescript-eslint/unbound-method */
@@ -15,8 +14,10 @@ describe('Array.fill', (): void => {
arrayFill = Array.prototype.fill;
u8aFill = Uint8Array.prototype.fill;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
Array.prototype.fill = null;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
Uint8Array.prototype.fill = null;
+5 -1
View File
@@ -13,9 +13,11 @@ if (!Array.prototype.fill) {
throw new TypeError('this is null or not defined');
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const A = Object(this);
// Steps 3-5.
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const len = A.length >>> 0;
// Steps 6-7.
@@ -38,17 +40,19 @@ if (!Array.prototype.fill) {
// Step 12.
while (k < final) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
A[k] = value;
k++;
}
// Step 13.
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return A;
};
}
if (!Uint8Array.prototype.fill) {
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
Uint8Array.prototype.fill = Array.prototype.fill;
}
+1 -1
View File
@@ -10,7 +10,7 @@ describe('String padEnd', (): void => {
beforeEach((): void => {
stringEnd = String.prototype.padEnd;
// eslint-disable-next-line no-extend-native,@typescript-eslint/no-explicit-any
// eslint-disable-next-line no-extend-native,@typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-assignment
String.prototype.padEnd = null as any;
require('./padEnd');
+1 -1
View File
@@ -10,7 +10,7 @@ describe('String padStart', (): void => {
beforeEach((): void => {
stringStart = String.prototype.padStart;
// eslint-disable-next-line no-extend-native,@typescript-eslint/no-explicit-any
// eslint-disable-next-line no-extend-native,@typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-assignment
String.prototype.padStart = null as any;
require('./padStart');
@@ -3,16 +3,14 @@
// of the Apache-2.0 license. See the LICENSE file for details.
/* eslint-disable no-proto */
/* eslint-disable @typescript-eslint/ban-ts-ignore */
/* eslint-disable @typescript-eslint/unbound-method */
describe('setPrototypeOf', (): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let orig: (o: any, proto: object | null) => any;
let orig: (o: Record<string, unknown>, proto: Record<string, unknown> | null) => Record<string, unknown>;
beforeEach((): void => {
orig = Object.setPrototypeOf;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
Object.setPrototypeOf = null;
@@ -27,6 +25,7 @@ describe('setPrototypeOf', (): void => {
const obj = {};
const proto = { foo: 'bar' };
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
expect(Object.setPrototypeOf(obj, proto).__proto__).toBe(proto);
});
});
+2 -5
View File
@@ -2,13 +2,10 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
/* eslint-disable @typescript-eslint/unbound-method */
// React Native does not have Object.setPrototypeOf
if (!Object.setPrototypeOf) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Object.setPrototypeOf = function (obj: any, proto: object | null): void {
// eslint-disable-next-line no-proto
Object.setPrototypeOf = function (obj: Record<string, unknown>, proto: Record<string, unknown> | null): Record<string, unknown> {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,no-proto
obj.__proto__ = proto;
return obj;
@@ -6,32 +6,32 @@ describe('TextDecoder', (): void => {
let origTD: TextDecoder;
beforeEach((): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
origTD = (global as any).TextDecoder;
});
afterEach((): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
(global as any).TextDecoder = origTD;
});
it('polyfills with no exceptions (without TextDecoder)', (): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
(global as any).TextDecoder = null;
// eslint-disable-next-line @typescript-eslint/no-var-requires
expect(require('./textDecoder')).toBeDefined();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
expect((global as any).TextDecoder).toBeDefined();
});
it('polyfills with no exceptions (with TextDecoder)', (): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-var-requires,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
(global as any).TextDecoder = require('util').TextDecoder;
// eslint-disable-next-line @typescript-eslint/no-var-requires
expect(require('./textDecoder')).toBeDefined();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
expect((global as any).TextDecoder).toBeDefined();
});
});
+4 -2
View File
@@ -4,8 +4,10 @@
if (typeof TextDecoder === 'undefined') {
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(global as any).TextDecoder = require('util').TextDecoder;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-var-requires
const { TextDecoder: UTD } = require('util') as { TextDecoder: { new(): TextDecoder } };
global.TextDecoder = UTD;
} catch (error) {
// noop
}
@@ -6,32 +6,32 @@ describe('TextEncoder', (): void => {
let origTE: TextEncoder;
beforeEach((): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
origTE = (global as any).TextEncoder;
});
afterEach((): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
(global as any).TextEncoder = origTE;
});
it('polyfills with no exceptions (without TextEncoder)', (): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
(global as any).TextEncoder = null;
// eslint-disable-next-line @typescript-eslint/no-var-requires
expect(require('./textEncoder')).toBeDefined();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
expect((global as any).TextEncoder).toBeDefined();
});
it('polyfills with no exceptions (with TextEncoder)', (): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-var-requires,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
(global as any).TextEncoder = require('util').TextEncoder;
// eslint-disable-next-line @typescript-eslint/no-var-requires
expect(require('./textEncoder')).toBeDefined();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
expect((global as any).TextEncoder).toBeDefined();
});
});
+18 -2
View File
@@ -4,8 +4,24 @@
if (typeof TextEncoder === 'undefined') {
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(global as any).TextEncoder = require('util').TextEncoder;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-var-requires
const { TextEncoder: UTE } = require('util') as { TextEncoder: { new(): TextEncoder } };
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-member-access
(global as any).TextEncoder = class {
#encoder: TextEncoder;
constructor () {
this.#encoder = new UTE();
}
// For a Jest 26.0.1 environment, Buffer !== Uint8Array
encode (value: string): Uint8Array {
const encoded = this.#encoder.encode(value);
return Uint8Array.from(encoded);
}
};
} catch (error) {
// noop
}
+2 -2
View File
@@ -22,7 +22,7 @@ describe('promisify', (): void => {
.then((): void => {
throw new Error('Received unexpected result');
})
.catch((error): void => {
.catch((error: Error): void => {
expect(error.message).toEqual('test reject');
});
});
@@ -38,7 +38,7 @@ describe('promisify', (): void => {
it('handles functions with parameters (reject)', (): Promise<void> => {
const fn = (a: number, b: boolean, c: string, cb: (error: Error | null, result?: [number, boolean, string]) => void): void =>
cb(new Error(`test reject: ${a},${b},${c}`));
cb(new Error(`test reject: ${a},${b.toString()},${c}`));
return promisify(null, fn, 3, 'string', true).catch((error: Error): void => {
expect(error.message).toEqual('test reject: 3,string,true');
+4 -5
View File
@@ -2,8 +2,6 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* @name promisify
* @summary Wraps an async callback into a `Promise`
@@ -19,9 +17,10 @@
* await promisify(null, (cb) => cb(new Error('error!'))); // rejects with `error!`
* ```
*/
export default function promisify (self: any, fn: Function, ...params: any[]): Promise<any> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function promisify <R = any> (self: unknown, fn: (...params: any) => any, ...params: any[]): Promise<R> {
return new Promise((resolve, reject): void => {
const handler = (error: Error | null, result?: any): void => {
const handler = (error: Error | null, result?: R): void => {
if (error) {
reject(error);
} else {
@@ -29,6 +28,6 @@ export default function promisify (self: any, fn: Function, ...params: any[]): P
}
};
fn.apply(self, [...params, handler]);
fn.apply(self, params.concat(handler));
});
}
+1 -13
View File
@@ -14,18 +14,6 @@ describe('stringShorten', (): void => {
it('returns the shortened value when > maxLength', (): void => {
expect(
stringShorten('0123456789', 3)
).toEqual('012..789');
});
it('returns undefined as undefined', (): void => {
expect(
stringShorten()
).toEqual('undefined');
});
it('returns non-string values as strings', (): void => {
expect(
stringShorten(12345678, 2)
).toEqual('12..78');
).toEqual('012789');
});
});
+3 -5
View File
@@ -6,7 +6,7 @@
* @name stringShorten
* @summary Returns a string with maximum length
* @description
* Checks the string against the `prefixLength`, if longer than dopuble this, shortens it by placing `..` in the middle of it
* Checks the string against the `prefixLength`, if longer than double this, shortens it by placing `..` in the middle of it
* @example
* <BR>
*
@@ -17,12 +17,10 @@
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function stringShorten (_value?: any, prefixLength = 6): string {
const value = `${_value}`;
export default function stringShorten (value: string, prefixLength = 6): string {
if (value.length <= 2 + 2 * prefixLength) {
return value;
}
return `${value.substr(0, prefixLength)}..${value.slice(-prefixLength)}`;
return `${value.substr(0, prefixLength)}${value.slice(-prefixLength)}`;
}
+1 -1
View File
@@ -8,7 +8,7 @@ describe('stringToU8a', (): void => {
it('decodes to an empty string for undefined', (): void => {
expect(
stringToU8a()
).toEqual(new Uint8Array([]));
).toEqual(new Uint8Array());
});
it('encodes the string correctly', (): void => {
+1 -1
View File
@@ -39,5 +39,5 @@ try {
export default function stringToU8a (value?: string): Uint8Array {
return value
? encoder.encode(value)
: new Uint8Array([]);
: new Uint8Array();
}
+3 -5
View File
@@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import BN from 'bn.js';
import type BN from 'bn.js';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export interface Constructor<T = any> {
@@ -20,10 +20,8 @@ export interface SiDef {
value: string;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Logger$Data$Fn = () => any[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type Logger$Data = (any | Logger$Data$Fn)[];
type Logger$Data$Fn = () => unknown[];
export type Logger$Data = (unknown | Logger$Data$Fn)[];
export interface Logger {
debug: (...values: Logger$Data) => void;
+16 -8
View File
@@ -21,15 +21,23 @@ import u8aToU8a from './toU8a';
* ); // [1, 2, 3, 4, 5, 6]
* ```
*/
export default function u8aConcat (..._list: (Uint8Array | string)[]): Uint8Array {
const list = _list.map(u8aToU8a);
const result = new Uint8Array(list.reduce((total, item): number => total + item.length, 0));
export default function u8aConcat (...list: (Uint8Array | string)[]): Uint8Array {
let length = 0;
let offset = 0;
const u8as = new Array(list.length) as Uint8Array[];
return list.reduce((result, item): Uint8Array => {
result.set(item, offset);
offset += item.length;
for (let i = 0; i < list.length; i++) {
u8as[i] = u8aToU8a(list[i]);
return result;
}, result);
length += u8as[i].length;
}
const result = new Uint8Array(length);
for (let i = 0; i < u8as.length; i++) {
result.set(u8as[i], offset);
offset += u8as[i].length;
}
return result;
}
+43
View File
@@ -0,0 +1,43 @@
// Copyright 2017-2020 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { u8aEq } from '.';
describe('u8aEq', (): void => {
it('returns false when the lengths do not match', (): void => {
expect(
u8aEq(
new Uint8Array([1, 2, 3]),
new Uint8Array([1, 2])
)
).toEqual(false);
});
it('returns false when the contents do not match', (): void => {
expect(
u8aEq(
new Uint8Array([1, 2, 3]),
new Uint8Array([1, 2, 4])
)
).toEqual(false);
});
it('returns true when the contents do match', (): void => {
expect(
u8aEq(
new Uint8Array([1, 2, 3]),
new Uint8Array([1, 2, 3])
)
).toEqual(true);
});
it('returns true with equalvalent hex & Uint8array', (): void => {
expect(
u8aEq(
'0x010203',
new Uint8Array([1, 2, 3])
)
).toEqual(true);
});
});
+37
View File
@@ -0,0 +1,37 @@
// Copyright 2017-2020 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import u8aToU8a from './toU8a';
function equals (a: Uint8Array, b: Uint8Array): boolean {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
/**
* @name u8aEq
* @summary Compares two Uint8Arrays.
* @description
* For `UInt8Array` (or hex string) input values true if there is a match.
* @example
* <BR>
*
* ```javascript
* import { u8aEq } from '@polkadot/util';
*
* u8aEq(new Uint8Array([0x68, 0x65]), new Uint8Array([0x68, 0x65])); // true
* ```
*/
export default function u8aEq (a: Uint8Array | string, b: Uint8Array | string): boolean {
return equals(u8aToU8a(a), u8aToU8a(b));
}
+1
View File
@@ -7,6 +7,7 @@
*/
export { default as u8aConcat } from './concat';
export { default as u8aEq } from './eq';
export { default as u8aFixLength } from './fixLength';
export { default as u8aSorted } from './sorted';
export { default as u8aToBn } from './toBn';

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