Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d1934060e0 | ||
|
|
6d9da39d8b | ||
|
|
4ed096024e | ||
|
|
ae36d58802 | ||
|
|
c8100dbe43 | ||
|
|
28d2ce38bd | ||
|
|
afce99ed1a | ||
|
|
29d13ab19c | ||
|
|
68a8bcb7db | ||
|
|
d2ecf1730a | ||
|
|
af56c10278 | ||
|
|
42f318fcb5 | ||
|
|
336df0d76d | ||
|
|
d85cedf5a0 | ||
|
|
a59187bce6 | ||
|
|
f9a5b75e10 | ||
|
|
87228149d4 | ||
|
|
67f36f6a13 | ||
|
|
75a9898daf | ||
|
|
0f726ce777 | ||
|
|
765f9baf44 | ||
|
|
2d181df360 | ||
|
|
77ff703a08 | ||
|
|
804ed13d0a | ||
|
|
341a6b0c08 | ||
|
|
614985b8ac | ||
|
|
d5bfa8c3c4 | ||
|
|
359981d2ef | ||
|
|
b0ee79f90c | ||
|
|
c2d595fb3f | ||
|
|
f837200a73 | ||
|
|
ea7dd553a2 | ||
|
|
7c1ca3a5c9 | ||
|
|
75cd547b49 | ||
|
|
91c4c407a9 | ||
|
|
20b46a65fa | ||
|
|
c60459e303 | ||
|
|
92ab4699b3 | ||
|
|
932f4c25f5 | ||
|
|
aaa35a8198 | ||
|
|
9708131620 | ||
|
|
c539430a0b | ||
|
|
8defc792a9 | ||
|
|
76a0daeed6 | ||
|
|
e236fdc396 | ||
|
|
e30dd7c0d9 | ||
|
|
f3ac6b2674 | ||
|
|
171015fbba | ||
|
|
dca36e41fd | ||
|
|
a602b0409c | ||
|
|
04d79da155 | ||
|
|
81a31519db | ||
|
|
78e39dcf34 | ||
|
|
6194660b3b | ||
|
|
2e08018718 | ||
|
|
b0d6ccdbd4 | ||
|
|
48b753b8ac | ||
|
|
506bc59f86 | ||
|
|
f86fcc6044 | ||
|
|
e8d2a439d5 | ||
|
|
9fa6b5bffa | ||
|
|
932ef41aae | ||
|
|
3910853ba1 | ||
|
|
6956e88708 | ||
|
|
3769b99cd2 | ||
|
|
ee17054b38 | ||
|
|
72cfbddd4a | ||
|
|
cffb23728d | ||
|
|
a69dc01c78 | ||
|
|
d889c71056 | ||
|
|
8eef3f9989 |
+2
-1
@@ -1 +1,2 @@
|
||||
4
|
||||
5
|
||||
2.6.2
|
||||
@@ -14,9 +14,19 @@ jobs:
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
- name: Config yarn cache
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
- uses: actions/cache@v1
|
||||
id: yarn-cache
|
||||
with:
|
||||
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-yarn-
|
||||
- name: lint
|
||||
run: |
|
||||
yarn install --frozen-lockfile
|
||||
yarn install --immutable | grep -v 'YN0013'
|
||||
yarn lint
|
||||
|
||||
test:
|
||||
@@ -31,11 +41,21 @@ jobs:
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
- name: Config yarn cache
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
- uses: actions/cache@v1
|
||||
id: yarn-cache
|
||||
with:
|
||||
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-yarn-
|
||||
- name: test
|
||||
env:
|
||||
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
|
||||
run: |
|
||||
yarn install --frozen-lockfile
|
||||
yarn install --immutable | grep -v 'YN0013'
|
||||
yarn test
|
||||
|
||||
build_code:
|
||||
@@ -50,9 +70,19 @@ jobs:
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
- name: Config yarn cache
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
- uses: actions/cache@v1
|
||||
id: yarn-cache
|
||||
with:
|
||||
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-yarn-
|
||||
- name: build
|
||||
run: |
|
||||
yarn install --frozen-lockfile
|
||||
yarn install --immutable | grep -v 'YN0013'
|
||||
yarn build
|
||||
|
||||
build_docs:
|
||||
@@ -67,7 +97,17 @@ jobs:
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
- name: Config yarn cache
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
- uses: actions/cache@v1
|
||||
id: yarn-cache
|
||||
with:
|
||||
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-yarn-
|
||||
- name: build
|
||||
run: |
|
||||
yarn install --frozen-lockfile
|
||||
yarn install --immutable | grep -v 'YN0013'
|
||||
yarn docs
|
||||
|
||||
@@ -20,6 +20,16 @@ jobs:
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
- name: Config yarn cache
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
- uses: actions/cache@v1
|
||||
id: yarn-cache
|
||||
with:
|
||||
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-yarn-
|
||||
- name: build
|
||||
env:
|
||||
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
|
||||
@@ -28,8 +38,8 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
yarn install --frozen-lockfile
|
||||
yarn polkadot-dev-ghact-build
|
||||
yarn install --immutable | grep -v 'YN0013'
|
||||
yarn polkadot-ci-ghact-build
|
||||
|
||||
build_docs:
|
||||
name: Build Docs
|
||||
@@ -44,6 +54,16 @@ jobs:
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
- name: Config yarn cache
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
- uses: actions/cache@v1
|
||||
id: yarn-cache
|
||||
with:
|
||||
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-yarn-
|
||||
- name: build
|
||||
env:
|
||||
GH_PAT: ${{ secrets.GH_PAT }}
|
||||
@@ -51,8 +71,8 @@ jobs:
|
||||
GH_PAGES_SRC: build-docs
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
yarn install --frozen-lockfile
|
||||
yarn polkadot-dev-ghact-docs
|
||||
yarn install --immutable | grep -v 'YN0013'
|
||||
yarn polkadot-ci-ghact-docs
|
||||
|
||||
dummy:
|
||||
name: Dummy
|
||||
|
||||
@@ -12,6 +12,10 @@ tmp/
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.npmrc
|
||||
.yarn/*
|
||||
!.yarn/releases
|
||||
!.yarn/plugins
|
||||
.pnp.*
|
||||
cc-test-reporter
|
||||
lerna-debug.log*
|
||||
npm-debug.log*
|
||||
|
||||
File diff suppressed because one or more lines are too long
+58
File diff suppressed because one or more lines are too long
+10
@@ -0,0 +1,10 @@
|
||||
enableImmutableInstalls: false
|
||||
enableProgressBars: false
|
||||
|
||||
nodeLinker: node-modules
|
||||
|
||||
plugins:
|
||||
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.js
|
||||
spec: "@yarnpkg/plugin-interactive-tools"
|
||||
|
||||
yarnPath: .yarn/releases/yarn-berry.js
|
||||
+123
-29
@@ -1,12 +1,42 @@
|
||||
# 2.2.1
|
||||
# 2.6.1 Feb 29, 2020
|
||||
|
||||
- Add resolved for jest requires (tests from src)
|
||||
- **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.
|
||||
- Add `cryptoIsReady (): boolean` function to check status of initialization
|
||||
- Add `addressCheckChecksum (decoded: Uint8Array)` as an helper to extract and verify the ss58 checksum
|
||||
- Swap to yarn 2, allow use in yan 2 projects
|
||||
|
||||
# 2.1.1
|
||||
# 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
|
||||
|
||||
- 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`
|
||||
- The `decimals` option to `formatBalance` should now be passed as part of the `options` (previous last-param deprecated)
|
||||
- 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
|
||||
|
||||
- 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 yarnpkg 2 (Explicit instead of implicit)
|
||||
|
||||
# 2.2.1 Feb 06, 2020
|
||||
|
||||
- Add resolver for jest requires (tests from src)
|
||||
|
||||
# 2.1.1 Feb 04, 2020
|
||||
|
||||
- Update `detectPackage(<package.json>, __dirname?)` with calling folder
|
||||
|
||||
# 2.0.1
|
||||
# 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)
|
||||
@@ -14,27 +44,27 @@
|
||||
- Renamed `assertSingletonPackage` to `detectPackage` with inclusion of version listing
|
||||
- Swap to elliptic library for secp2561 recovery (No node bindings)
|
||||
|
||||
# 1.8.1
|
||||
# 1.8.1 Jan 09, 2020
|
||||
|
||||
- Add cross-client encryption/decryption support (Thanks to https://github.com/hskang9)
|
||||
|
||||
# 1.7.1
|
||||
# 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
|
||||
# 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
|
||||
# 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
|
||||
# 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`
|
||||
@@ -42,25 +72,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
|
||||
# 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
|
||||
# 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
|
||||
# 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
|
||||
# 1.0.1 Aug 02, 2019
|
||||
|
||||
- `formatBalance` now allows for `Compact` inputs
|
||||
- `formaBalance` now allows correct formatting of very large decimals
|
||||
|
||||
# 0.94.1
|
||||
# 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)
|
||||
@@ -68,7 +98,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
|
||||
# 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)`
|
||||
@@ -76,69 +106,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
|
||||
# 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
|
||||
# 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
|
||||
# 0.90.1 May 08, 2019
|
||||
|
||||
- Moving towards 1.0
|
||||
- Added bnMin & bnMax functions
|
||||
|
||||
# 0.76.1
|
||||
# 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
|
||||
# 0.75.1 Mar 29, 2019
|
||||
|
||||
- Start journey to 1.0
|
||||
|
||||
# 0.42.1
|
||||
# 0.42.1 Mar 28, 2019
|
||||
|
||||
- Add `assertSingletonPackage` to util
|
||||
- Ensure that only a single keyring instance is loaded (uses above)
|
||||
|
||||
# 0.41.1
|
||||
# 0.41.1 Mar 25, 2019
|
||||
|
||||
- Extensions to the client-specific database interfaces (non-breaking for API and util users)
|
||||
|
||||
# 0.40.1
|
||||
# 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
|
||||
# 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
|
||||
# 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
|
||||
# 0.37.1 Mar 14, 2019
|
||||
|
||||
- Swap to publishing -beta.x on merge (non-breaking testing)
|
||||
|
||||
# 0.36.1
|
||||
# 0.36.1 Mar 13, 2019
|
||||
|
||||
- Add `fromUri` to keyring along with hard & soft key derivation.
|
||||
|
||||
# 0.35.1
|
||||
# 0.35.1 Mar 04, 2019
|
||||
|
||||
- Remove NodeJs-only `syncify` function, not exported by the package (with binary dependency for Node)
|
||||
|
||||
# 0.34.1
|
||||
# 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.32.1 Oct 18, 2018
|
||||
|
||||
# 0.31.1 Oct 12, 2018
|
||||
|
||||
# 0.30.1 Sep 11, 2018
|
||||
|
||||
# 0.29.1 Sep 01, 2018
|
||||
|
||||
# 0.28.1 Aug 11, 2018
|
||||
|
||||
# 0.27.1 Aug 06, 2018
|
||||
|
||||
# 0.26.1 Jun 27, 2018
|
||||
|
||||
# 0.25.1 Jun 26, 2018
|
||||
|
||||
# 0.24.1 Jun 22, 2018
|
||||
|
||||
# 0.23.1 Jun 21, 2018
|
||||
|
||||
# 0.22.1 May 24, 2018
|
||||
|
||||
# 0.21.1 May 17, 2018
|
||||
|
||||
# 0.20.1 May 16, 2018
|
||||
|
||||
# 0.19.1 Apr 19, 2018
|
||||
|
||||
# 0.18.1 Mar 20, 2018
|
||||
|
||||
# 0.17.1 Mar0 8, 2018
|
||||
|
||||
# 0.16.1 Feb 23, 2018
|
||||
|
||||
# 0.15.1 Feb 15, 2018
|
||||
|
||||
# 0.14.1 Feb 07, 2018
|
||||
|
||||
# 0.13.1 Jan 25, 2018
|
||||
|
||||
# 0.12.1 Jan 11, 2018
|
||||
|
||||
# 0.11.1 Dec 30, 2017
|
||||
|
||||
# 0.10.1 Dec 17, 2017
|
||||
|
||||
# 0.9.1 Dec 14, 2017
|
||||
|
||||
# 0.8.1 Dec 12, 2017
|
||||
|
||||
# 0.7.1 Dec 11, 2017
|
||||
|
||||
# 0.6.1 Nov 30, 2017
|
||||
|
||||
# 0.5.1 Nov 20, 2017
|
||||
|
||||
# 0.4.1 Nov 19, 2017
|
||||
|
||||
# 0.3.1 Nov 19, 2017
|
||||
|
||||
# 0.2.1 Nov 18, 2017
|
||||
|
||||
+1
-3
@@ -1,3 +1 @@
|
||||
module.exports = {
|
||||
extends: '@polkadot/dev/config/babel'
|
||||
};
|
||||
module.exports = require('@polkadot/dev/config/babel');
|
||||
|
||||
+1
-7
@@ -8,15 +8,9 @@ module.exports = Object.assign({}, config, {
|
||||
'@polkadot/util(.*)$': '<rootDir>/packages/util/src/$1'
|
||||
},
|
||||
modulePathIgnorePatterns: [
|
||||
'<rootDir>/packages/db/build',
|
||||
'<rootDir>/packages/chainspec/build',
|
||||
'<rootDir>/packages/keyring/build',
|
||||
'<rootDir>/packages/trie-codec/build',
|
||||
'<rootDir>/packages/trie-db/build',
|
||||
'<rootDir>/packages/trie-hash/build',
|
||||
'<rootDir>/packages/util/build',
|
||||
'<rootDir>/packages/util-crypto/build',
|
||||
'<rootDir>/packages/util-rlp/build'
|
||||
'<rootDir>/packages/util-crypto/build'
|
||||
],
|
||||
resolver: './jest.resolver.js'
|
||||
});
|
||||
|
||||
+4
-7
@@ -1,15 +1,12 @@
|
||||
// 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.
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const path = require('path');
|
||||
|
||||
module.exports = function resolver (file, config) {
|
||||
if (file.includes('package.json')) {
|
||||
console.error(file, config);
|
||||
return path.join(config.basedir.replace('/src', '/'), file);
|
||||
}
|
||||
|
||||
return config.defaultResolver(file, config);
|
||||
return file.includes('package.json')
|
||||
? path.join(config.basedir.replace('/src', '/'), file)
|
||||
: config.defaultResolver(file, config);
|
||||
};
|
||||
|
||||
+1
-1
@@ -9,5 +9,5 @@
|
||||
"packages": [
|
||||
"packages/*"
|
||||
],
|
||||
"version": "2.2.1"
|
||||
"version": "2.6.2"
|
||||
}
|
||||
|
||||
+10
-12
@@ -1,28 +1,26 @@
|
||||
{
|
||||
"version": "2.2.1",
|
||||
"repository": "https://github.com/polkadot-js/common",
|
||||
"author": "Jaco Greeff <jacogr@gmail.com>",
|
||||
"license": "Apache-2",
|
||||
"private": true,
|
||||
"engines": {
|
||||
"yarn": "^1.10.1"
|
||||
},
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
"resolutions": {
|
||||
"babel-core": "^7.0.0-bridge.0",
|
||||
"typescript": "^3.7.5"
|
||||
"typescript": "^3.8.3"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "polkadot-dev-build-ts",
|
||||
"docs": "polkadot-dev-build-docs",
|
||||
"lint": "eslint . --ext .js,.jsx,.ts,.tsx . && tsc --noEmit --pretty",
|
||||
"lint": "polkadot-dev-run-lint",
|
||||
"clean": "polkadot-dev-clean-build",
|
||||
"postinstall": "polkadot-dev-yarn-only",
|
||||
"test": "jest --coverage --runInBand",
|
||||
"test:one": "jest"
|
||||
"test": "polkadot-dev-run-test --coverage --runInBand",
|
||||
"test:one": "polkadot-dev-run-test"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.8.3",
|
||||
"@polkadot/dev": "^0.33.3",
|
||||
"@polkadot/ts": "^0.2.1"
|
||||
"@babel/core": "^7.8.7",
|
||||
"@polkadot/dev": "^0.50.30",
|
||||
"@polkadot/ts": "^0.3.7"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/keyring",
|
||||
"version": "2.2.1",
|
||||
"version": "2.6.2",
|
||||
"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.8.3",
|
||||
"@polkadot/util": "^2.2.1",
|
||||
"@polkadot/util-crypto": "^2.2.1"
|
||||
"@babel/runtime": "^7.8.7",
|
||||
"@polkadot/util": "2.6.2",
|
||||
"@polkadot/util-crypto": "2.6.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { hexToU8a, stringToU8a } from '@polkadot/util';
|
||||
import { cryptoWaitReady, setSS58Format } from '@polkadot/util-crypto';
|
||||
import { cryptoWaitReady, setSS58Format, encodeAddress } from '@polkadot/util-crypto';
|
||||
|
||||
import Keyring from '.';
|
||||
|
||||
@@ -17,57 +17,55 @@ describe('keypair', (): void => {
|
||||
const publicKeyTwo = new Uint8Array([215, 90, 152, 1, 130, 177, 10, 183, 213, 75, 254, 211, 201, 100, 7, 58, 14, 225, 114, 243, 218, 166, 35, 37, 175, 2, 26, 104, 247, 7, 81, 26]);
|
||||
const seedOne = stringToU8a('12345678901234567890123456789012');
|
||||
const seedTwo = hexToU8a('0x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60');
|
||||
let keypair: Keyring;
|
||||
let keyring: Keyring;
|
||||
|
||||
beforeEach((): void => {
|
||||
keypair = new Keyring({ type: 'ed25519' });
|
||||
keyring = new Keyring({ ss58Format: 42, type: 'ed25519' });
|
||||
|
||||
keypair.addFromSeed(seedOne, {});
|
||||
});
|
||||
|
||||
afterEach((): void => {
|
||||
setSS58Format(42);
|
||||
keyring.addFromSeed(seedOne, {});
|
||||
});
|
||||
|
||||
it('adds the pair', (): void => {
|
||||
expect(
|
||||
keypair.addFromSeed(seedTwo, {}).publicKey
|
||||
keyring.addFromSeed(seedTwo, {}).publicKey
|
||||
).toEqual(publicKeyTwo);
|
||||
});
|
||||
|
||||
it('creates a ed25519 pair via mnemonicToSeed', (): void => {
|
||||
expect(
|
||||
keypair.addFromUri(
|
||||
keyring.addFromUri(
|
||||
'seed sock milk update focus rotate barely fade car face mechanic mercy'
|
||||
).address
|
||||
).toEqual('5DkQP32jP4DVJLWWBRBoZF2tpWjqFrcrTBo6H5NcSk7MxKCC');
|
||||
});
|
||||
|
||||
it('adds from a mnemonic', (): void => {
|
||||
setSS58Format(68);
|
||||
it('adds from a mnemonic, with correct ss58', (): void => {
|
||||
setSS58Format(20); // this would not be used
|
||||
keyring.setSS58Format(68); // this would be used
|
||||
|
||||
expect(
|
||||
keypair.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {}).address
|
||||
).toEqual('7sPsxWPE5DzAyPT3VuoJYw5NTGscx9QYN9oddQx4kALKC3hH');
|
||||
const pair = keyring.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {});
|
||||
|
||||
expect(pair.address).toEqual('7sPsxWPE5DzAyPT3VuoJYw5NTGscx9QYN9oddQx4kALKC3hH');
|
||||
expect(encodeAddress(pair.publicKey)).toEqual('35cDYtPsdG1HUa2n2MaARgJyRz1WKMBZK1DL6c5cX7nugQh1');
|
||||
});
|
||||
|
||||
it('allows publicKeys retrieval', (): void => {
|
||||
keypair.addFromSeed(seedTwo, {});
|
||||
keyring.addFromSeed(seedTwo, {});
|
||||
|
||||
expect(
|
||||
keypair.getPublicKeys()
|
||||
keyring.getPublicKeys()
|
||||
).toEqual([publicKeyOne, publicKeyTwo]);
|
||||
});
|
||||
|
||||
it('allows retrieval of a specific item', (): void => {
|
||||
expect(
|
||||
keypair.getPair(publicKeyOne).publicKey
|
||||
keyring.getPair(publicKeyOne).publicKey
|
||||
).toEqual(publicKeyOne);
|
||||
});
|
||||
|
||||
it('allows adding from JSON', (): void => {
|
||||
expect(
|
||||
keypair.addFromJson(
|
||||
keyring.addFromJson(
|
||||
JSON.parse('{"address":"5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua","encoded":"0xb4a14995d25ab609f3686e9fa45f1fb237cd833f33f00d4b12c51858ca070d96972e47d73aae5eeb0fc06f923826cf0943fdb02c2c2ee30ef52a7912663053940d1da4da66b3a3f520ae07422c1c94b2d95690fca9d1f4a997623bb2923a8833280e19e7f72c3c5cfa343974e60e2b3dc53b404fdaf330756daad5e4e3","encoding":{"content":"pkcs8","type":"xsalsa20-poly1305","version":"0"},"meta":{"isTesting":true,"name":"alice"}}')
|
||||
).publicKey
|
||||
).toEqual(
|
||||
@@ -77,7 +75,7 @@ describe('keypair', (): void => {
|
||||
|
||||
it('signs and verifies', (): void => {
|
||||
const MESSAGE = stringToU8a('this is a message');
|
||||
const pair = keypair.getPair(publicKeyOne);
|
||||
const pair = keyring.getPair(publicKeyOne);
|
||||
const signature = pair.sign(MESSAGE);
|
||||
|
||||
expect(pair.verify(MESSAGE, signature)).toBe(true);
|
||||
@@ -89,55 +87,51 @@ describe('keypair', (): void => {
|
||||
const publicKeyTwo = hexToU8a('0x44a996beb1eef7bdcab976ab6d2ca26104834164ecf28fb375600576fcc6eb0f');
|
||||
const seedOne = stringToU8a('12345678901234567890123456789012');
|
||||
const seedTwo = hexToU8a('0x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60');
|
||||
let keypair: Keyring;
|
||||
let keyring: Keyring;
|
||||
|
||||
beforeEach((): void => {
|
||||
keypair = new Keyring({ type: 'sr25519' });
|
||||
keyring = new Keyring({ ss58Format: 42, type: 'sr25519' });
|
||||
|
||||
keypair.addFromSeed(seedOne, {});
|
||||
});
|
||||
|
||||
afterEach((): void => {
|
||||
setSS58Format(42);
|
||||
keyring.addFromSeed(seedOne, {});
|
||||
});
|
||||
|
||||
it('creates with dev phrase when only path specified', (): void => {
|
||||
expect(
|
||||
keypair.createFromUri('//Alice').address
|
||||
keyring.createFromUri('//Alice').address
|
||||
).toEqual('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY');
|
||||
});
|
||||
|
||||
it('adds the pair', (): void => {
|
||||
expect(
|
||||
keypair.addFromSeed(seedTwo, {}).publicKey
|
||||
keyring.addFromSeed(seedTwo, {}).publicKey
|
||||
).toEqual(publicKeyTwo);
|
||||
});
|
||||
|
||||
it('adds from a mnemonic', (): void => {
|
||||
setSS58Format(68);
|
||||
keyring.setSS58Format(68);
|
||||
|
||||
expect(
|
||||
keypair.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {}).address
|
||||
keyring.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {}).address
|
||||
).toEqual('7qQGarA4PWjPPVHG4USn1yuuVZvEHN7XZz8o7EbAp48jayZQ');
|
||||
});
|
||||
|
||||
it('allows publicKeys retrieval', (): void => {
|
||||
keypair.addFromSeed(seedTwo, {});
|
||||
keyring.addFromSeed(seedTwo, {});
|
||||
|
||||
expect(
|
||||
keypair.getPublicKeys()
|
||||
keyring.getPublicKeys()
|
||||
).toEqual([publicKeyOne, publicKeyTwo]);
|
||||
});
|
||||
|
||||
it('allows retrieval of a specific item', (): void => {
|
||||
expect(
|
||||
keypair.getPair(publicKeyOne).publicKey
|
||||
keyring.getPair(publicKeyOne).publicKey
|
||||
).toEqual(publicKeyOne);
|
||||
});
|
||||
|
||||
it('allows adding from JSON', (): void => {
|
||||
expect(
|
||||
keypair.addFromJson(
|
||||
keyring.addFromJson(
|
||||
JSON.parse('{"address":"5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua","encoded":"0xb4a14995d25ab609f3686e9fa45f1fb237cd833f33f00d4b12c51858ca070d96972e47d73aae5eeb0fc06f923826cf0943fdb02c2c2ee30ef52a7912663053940d1da4da66b3a3f520ae07422c1c94b2d95690fca9d1f4a997623bb2923a8833280e19e7f72c3c5cfa343974e60e2b3dc53b404fdaf330756daad5e4e3","encoding":{"content":"pkcs8","type":"xsalsa20-poly1305","version":"0"},"meta":{"isTesting":true,"name":"alice"}}')
|
||||
).publicKey
|
||||
).toEqual(
|
||||
@@ -147,7 +141,7 @@ describe('keypair', (): void => {
|
||||
|
||||
it('signs and verifies', (): void => {
|
||||
const MESSAGE = stringToU8a('this is a message');
|
||||
const pair = keypair.getPair(publicKeyOne);
|
||||
const pair = keyring.getPair(publicKeyOne);
|
||||
const signature = pair.sign(MESSAGE);
|
||||
|
||||
expect(pair.verify(MESSAGE, signature)).toBe(true);
|
||||
|
||||
@@ -7,13 +7,8 @@ import { decodeAddress, encodeAddress, setSS58Format } from '@polkadot/util-cryp
|
||||
|
||||
import Keyring from './keyring';
|
||||
|
||||
// eslint-disable-next-line no-useless-catch
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
detectPackage(require('./package.json'), __dirname);
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
detectPackage(require('./package.json'), typeof __dirname !== 'undefined' && __dirname);
|
||||
|
||||
export default Keyring;
|
||||
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
import { KeypairType } from '@polkadot/util-crypto/types';
|
||||
import { KeyringInstance, KeyringPair, KeyringPair$Json, KeyringPair$Meta, KeyringOptions } from './types';
|
||||
|
||||
import { assert, hexToU8a, isNumber, isHex, stringToU8a } from '@polkadot/util';
|
||||
import { decodeAddress, encodeAddress, keyExtractSuri, keyFromPath, naclKeypairFromSeed as naclFromSeed, schnorrkelKeypairFromSeed as schnorrkelFromSeed, mnemonicToMiniSecret, setSS58Format } from '@polkadot/util-crypto';
|
||||
import { assert, hexToU8a, isHex, stringToU8a } from '@polkadot/util';
|
||||
import { decodeAddress, encodeAddress, keyExtractSuri, keyFromPath, naclKeypairFromSeed as naclFromSeed, schnorrkelKeypairFromSeed as schnorrkelFromSeed, mnemonicToMiniSecret } from '@polkadot/util-crypto';
|
||||
|
||||
import { DEV_PHRASE } from './defaults';
|
||||
import createPair from './pair';
|
||||
@@ -29,30 +29,22 @@ import Pairs from './pairs';
|
||||
* an account may be obtained using `toJson` accompanied by the account passphrase.
|
||||
*/
|
||||
export default class Keyring implements KeyringInstance {
|
||||
private _pairs: Pairs;
|
||||
readonly #pairs: Pairs;
|
||||
|
||||
private _type: KeypairType;
|
||||
readonly #type: KeypairType;
|
||||
|
||||
#ss58?: number;
|
||||
|
||||
public decodeAddress = decodeAddress;
|
||||
|
||||
public encodeAddress = encodeAddress;
|
||||
|
||||
public setSS58Format = setSS58Format;
|
||||
|
||||
constructor (options: KeyringOptions = {}) {
|
||||
options.type = options.type || 'ed25519';
|
||||
options.ss58Format = isNumber(options.ss58Format)
|
||||
? options.addressPrefix
|
||||
: options.ss58Format;
|
||||
|
||||
assert(options && ['ed25519', 'sr25519'].includes(options.type || 'undefined'), `Expected a keyring type of either 'ed25519' or 'sr25519', found '${options.type}`);
|
||||
|
||||
this._pairs = new Pairs();
|
||||
this._type = options.type;
|
||||
|
||||
if (isNumber(options.ss58Format)) {
|
||||
setSS58Format(options.ss58Format);
|
||||
}
|
||||
this.#pairs = new Pairs();
|
||||
this.#ss58 = options.ss58Format;
|
||||
this.#type = options.type;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -73,7 +65,7 @@ export default class Keyring implements KeyringInstance {
|
||||
* @description Returns the type of the keyring, either ed25519 of sr25519
|
||||
*/
|
||||
public get type (): KeypairType {
|
||||
return this._type;
|
||||
return this.#type;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -81,7 +73,7 @@ export default class Keyring implements KeyringInstance {
|
||||
* @summary Stores an account, given a keyring pair, as a Key/Value (public key, pair) in Keyring Pair Dictionary
|
||||
*/
|
||||
public addPair (pair: KeyringPair): KeyringPair {
|
||||
return this._pairs.add(pair);
|
||||
return this.#pairs.add(pair);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -95,7 +87,7 @@ export default class Keyring implements KeyringInstance {
|
||||
public addFromAddress (address: string | Uint8Array, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null = null, type: KeypairType = this.type, ignoreChecksum?: boolean): KeyringPair {
|
||||
const publicKey = this.decodeAddress(address, ignoreChecksum);
|
||||
|
||||
return this.addPair(createPair(type, { publicKey, secretKey: new Uint8Array(64) }, meta, encoded));
|
||||
return this.addPair(createPair({ toSS58: this.encodeAddress, type }, { publicKey, secretKey: new Uint8Array(64) }, meta, encoded));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -137,7 +129,7 @@ export default class Keyring implements KeyringInstance {
|
||||
? schnorrkelFromSeed(seed)
|
||||
: naclFromSeed(seed);
|
||||
|
||||
return this.addPair(createPair(type, keypair, meta, null));
|
||||
return this.addPair(createPair({ toSS58: this.encodeAddress, type }, keypair, meta, null));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -153,7 +145,7 @@ export default class Keyring implements KeyringInstance {
|
||||
|
||||
/**
|
||||
* @name createFromUri
|
||||
* @summry Creates a Keypair from an suri
|
||||
* @summary Creates a Keypair from an suri
|
||||
* @description This creates a pair from the suri, but does not add it to the keyring
|
||||
*/
|
||||
public createFromUri (_suri: string, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair {
|
||||
@@ -188,7 +180,15 @@ export default class Keyring implements KeyringInstance {
|
||||
: naclFromSeed(seed);
|
||||
const derived = keyFromPath(keypair, path, type);
|
||||
|
||||
return createPair(type, derived, meta, null);
|
||||
return createPair({ toSS58: this.encodeAddress, type }, derived, meta, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @name encodeAddress
|
||||
* @description Encodes the input into an ss58 representation
|
||||
*/
|
||||
public encodeAddress = (key: Uint8Array | string, ss58Format?: number): string => {
|
||||
return encodeAddress(key, ss58Format || this.#ss58);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -198,7 +198,7 @@ export default class Keyring implements KeyringInstance {
|
||||
* a key lookup using the provided account address or public key (after decoding it).
|
||||
*/
|
||||
public getPair (address: string | Uint8Array): KeyringPair {
|
||||
return this._pairs.get(address);
|
||||
return this.#pairs.get(address);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -207,7 +207,7 @@ export default class Keyring implements KeyringInstance {
|
||||
* @description Returns an array list of all the keyring pair values that are stored in the keyring pair dictionary.
|
||||
*/
|
||||
public getPairs (): KeyringPair[] {
|
||||
return this._pairs.all();
|
||||
return this.#pairs.all();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -216,7 +216,7 @@ export default class Keyring implements KeyringInstance {
|
||||
* @description Returns an array list of all the public keys associated with each of the keyring pair values that are stored in the keyring pair dictionary.
|
||||
*/
|
||||
public getPublicKeys (): Uint8Array[] {
|
||||
return this._pairs
|
||||
return this.#pairs
|
||||
.all()
|
||||
.map(({ publicKey }): Uint8Array =>
|
||||
publicKey
|
||||
@@ -228,7 +228,15 @@ export default class Keyring implements KeyringInstance {
|
||||
* @description Deletes the provided input address or public key from the stored Keyring Pair Dictionary.
|
||||
*/
|
||||
public removePair (address: string | Uint8Array): void {
|
||||
this._pairs.remove(address);
|
||||
this.#pairs.remove(address);
|
||||
}
|
||||
|
||||
/**
|
||||
* @name setSS58Format;
|
||||
* @description Sets the ss58 format for the keyring
|
||||
*/
|
||||
public setSS58Format (ss58: number): void {
|
||||
this.#ss58 = ss58;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -240,6 +248,6 @@ export default class Keyring implements KeyringInstance {
|
||||
* may backup their account to a JSON file that contains this information.
|
||||
*/
|
||||
public toJson (address: string | Uint8Array, passphrase?: string): KeyringPair$Json {
|
||||
return this._pairs.get(address).toJson(passphrase);
|
||||
return this.#pairs.get(address).toJson(passphrase);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,19 +14,7 @@ type DecodeResult = PairInfo & {
|
||||
secretKey: Uint8Array;
|
||||
};
|
||||
|
||||
export default function decode (passphrase?: string, encrypted?: Uint8Array | null): DecodeResult {
|
||||
assert(encrypted, 'No encrypted data available to decode');
|
||||
|
||||
const encoded = passphrase
|
||||
? (naclDecrypt(
|
||||
encrypted.subarray(NONCE_LENGTH),
|
||||
encrypted.subarray(0, NONCE_LENGTH),
|
||||
u8aFixLength(stringToU8a(passphrase), 256, true)
|
||||
) as Uint8Array)
|
||||
: encrypted;
|
||||
|
||||
assert(encoded, 'Unable to unencrypt using the supplied passphrase');
|
||||
|
||||
function decodePkcs8 (encoded: Uint8Array): DecodeResult {
|
||||
const header = encoded.subarray(0, PKCS8_HEADER.length);
|
||||
|
||||
assert(header.toString() === PKCS8_HEADER.toString(), 'Invalid Pkcs8 header found in body');
|
||||
@@ -52,3 +40,19 @@ export default function decode (passphrase?: string, encrypted?: Uint8Array | nu
|
||||
secretKey
|
||||
};
|
||||
}
|
||||
|
||||
export default function decode (passphrase?: string, encrypted?: Uint8Array | null): DecodeResult {
|
||||
assert(encrypted, 'No encrypted data available to decode');
|
||||
|
||||
const encoded = passphrase
|
||||
? naclDecrypt(
|
||||
encrypted.subarray(NONCE_LENGTH),
|
||||
encrypted.subarray(0, NONCE_LENGTH),
|
||||
u8aFixLength(stringToU8a(passphrase), 256, true)
|
||||
)
|
||||
: encrypted;
|
||||
|
||||
assert(encoded, 'Unable to unencrypt using the supplied passphrase');
|
||||
|
||||
return decodePkcs8(encoded);
|
||||
}
|
||||
|
||||
@@ -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 { cryptoWaitReady, setSS58Format } from '@polkadot/util-crypto';
|
||||
import { cryptoWaitReady, encodeAddress as toSS58, setSS58Format } from '@polkadot/util-crypto';
|
||||
|
||||
import { PAIRS } from '../testing';
|
||||
import testingPairs from '../testingPairs';
|
||||
@@ -79,14 +79,14 @@ describe('pair', (): void => {
|
||||
const PASS = 'testing';
|
||||
const encoded = keyring.alice.encodePkcs8(PASS);
|
||||
|
||||
const pair = createPair('sr25519', { publicKey: keyring.alice.publicKey });
|
||||
const pair = createPair({ toSS58, type: 'sr25519' }, { publicKey: keyring.alice.publicKey });
|
||||
pair.decodePkcs8(PASS, encoded);
|
||||
|
||||
expect(pair.isLocked).toEqual(false);
|
||||
});
|
||||
|
||||
it('allows derivation on the pair', (): void => {
|
||||
const alice = createPair('sr25519', { publicKey: PAIRS[0].publicKey, secretKey: PAIRS[0].secretKey }, {});
|
||||
const alice = createPair({ toSS58, type: 'sr25519' }, { publicKey: PAIRS[0].publicKey, secretKey: PAIRS[0].secretKey }, {});
|
||||
const stash = alice.derive('//stash');
|
||||
const soft = alice.derive('//funding/0');
|
||||
|
||||
|
||||
@@ -7,12 +7,17 @@ import { KeyringPair, KeyringPair$Json, KeyringPair$Meta, SignOptions } from '..
|
||||
import { PairInfo } from './types';
|
||||
|
||||
import { u8aConcat, assert } from '@polkadot/util';
|
||||
import { encodeAddress, keyExtractPath, keyFromPath, naclKeypairFromSeed as naclFromSeed, naclSign, naclVerify, schnorrkelKeypairFromSeed as schnorrkelFromSeed, schnorrkelSign, schnorrkelVerify } from '@polkadot/util-crypto';
|
||||
import { keyExtractPath, keyFromPath, naclKeypairFromSeed as naclFromSeed, naclSign, naclVerify, schnorrkelKeypairFromSeed as schnorrkelFromSeed, schnorrkelSign, schnorrkelVerify } from '@polkadot/util-crypto';
|
||||
|
||||
import decode from './decode';
|
||||
import encode from './encode';
|
||||
import toJson from './toJson';
|
||||
|
||||
interface Setup {
|
||||
toSS58: (publicKey: Uint8Array) => string;
|
||||
type: KeypairType;
|
||||
}
|
||||
|
||||
const SIG_TYPE_NONE = new Uint8Array();
|
||||
const SIG_TYPE_ED25519 = new Uint8Array([0]);
|
||||
const SIG_TYPE_SR25519 = new Uint8Array([1]);
|
||||
@@ -88,10 +93,10 @@ function verify (type: KeypairType, message: Uint8Array, signature: Uint8Array,
|
||||
* an `encoded` property that is assigned with the encoded public key in hex format, and an `encoding`
|
||||
* property that indicates whether the public key value of the `encoded` property is encoded or not.
|
||||
*/
|
||||
export default function createPair (type: KeypairType, { publicKey, secretKey }: PairInfo, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null = null): KeyringPair {
|
||||
export default function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: PairInfo, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null = null): KeyringPair {
|
||||
return {
|
||||
get address (): string {
|
||||
return encodeAddress(publicKey);
|
||||
return toSS58(publicKey);
|
||||
},
|
||||
get meta (): KeyringPair$Meta {
|
||||
return meta;
|
||||
@@ -124,7 +129,7 @@ export default function createPair (type: KeypairType, { publicKey, secretKey }:
|
||||
const { path } = keyExtractPath(suri);
|
||||
const derived = keyFromPath({ publicKey, secretKey: secretKey }, path, type);
|
||||
|
||||
return createPair(type, derived, meta, null);
|
||||
return createPair({ toSS58, type }, derived, meta, null);
|
||||
},
|
||||
encodePkcs8: (passphrase?: string): Uint8Array =>
|
||||
encode({ publicKey, secretKey }, passphrase),
|
||||
|
||||
@@ -10,24 +10,20 @@ import { decodeAddress } from '@polkadot/util-crypto';
|
||||
type KeyringPairMap = Record<string, KeyringPair>;
|
||||
|
||||
export default class Pairs implements KeyringPairs {
|
||||
private _map: KeyringPairMap;
|
||||
|
||||
constructor () {
|
||||
this._map = {};
|
||||
}
|
||||
readonly #map: KeyringPairMap = {};
|
||||
|
||||
public add (pair: KeyringPair): KeyringPair {
|
||||
this._map[pair.publicKey.toString()] = pair;
|
||||
this.#map[pair.publicKey.toString()] = pair;
|
||||
|
||||
return pair;
|
||||
}
|
||||
|
||||
public all (): KeyringPair[] {
|
||||
return Object.values(this._map);
|
||||
return Object.values(this.#map);
|
||||
}
|
||||
|
||||
public get (address: string | Uint8Array): KeyringPair {
|
||||
const pair = this._map[decodeAddress(address).toString()];
|
||||
const pair = this.#map[decodeAddress(address).toString()];
|
||||
|
||||
assert(pair, (): string => {
|
||||
const formatted: string = isU8a(address) || isHex(address)
|
||||
@@ -41,6 +37,6 @@ export default class Pairs implements KeyringPairs {
|
||||
}
|
||||
|
||||
public remove (address: string | Uint8Array): void {
|
||||
delete this._map[decodeAddress(address).toString()];
|
||||
delete this.#map[decodeAddress(address).toString()];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ export const PAIRS: PairDef[] = [
|
||||
export default function testKeyring (options: KeyringOptions = {}, isDerived = true): KeyringInstance {
|
||||
const keyring = new Keyring(options);
|
||||
|
||||
PAIRS.forEach(({ name, publicKey, secretKey, seed, type }): void => {
|
||||
PAIRS.forEach(({ name, publicKey, secretKey, seed, type = 'sr25519' }): void => {
|
||||
const meta = {
|
||||
isTesting: true,
|
||||
name: name || seed.replace('//', '_').toLowerCase()
|
||||
@@ -82,7 +82,7 @@ export default function testKeyring (options: KeyringOptions = {}, isDerived = t
|
||||
const pair = !isDerived && !name
|
||||
? keyring.addFromUri(seed, meta, options.type)
|
||||
: keyring.addPair(
|
||||
createPair(type || 'sr25519', { publicKey, secretKey }, meta)
|
||||
createPair({ toSS58: keyring.encodeAddress, type }, { publicKey, secretKey }, meta)
|
||||
);
|
||||
|
||||
pair.lock = (): void => {
|
||||
|
||||
@@ -7,8 +7,6 @@ import { Prefix } from '@polkadot/util-crypto/address/types';
|
||||
import { KeypairType } from '@polkadot/util-crypto/types';
|
||||
|
||||
export interface KeyringOptions {
|
||||
// @deprecated
|
||||
addressPrefix?: Prefix;
|
||||
ss58Format?: Prefix;
|
||||
type?: KeypairType;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/util-crypto",
|
||||
"version": "2.2.1",
|
||||
"version": "2.6.2",
|
||||
"description": "A collection of useful crypto utilities for @polkadot",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -25,20 +25,25 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util-crypto#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.8.3",
|
||||
"@polkadot/util": "^2.2.1",
|
||||
"@polkadot/wasm-crypto": "^0.20.1",
|
||||
"@types/bs58": "^4.0.0",
|
||||
"@types/elliptic": "^6.4.12",
|
||||
"@types/pbkdf2": "^3.0.0",
|
||||
"@types/xxhashjs": "^0.2.1",
|
||||
"base-x": "^3.0.7",
|
||||
"@babel/runtime": "^7.8.7",
|
||||
"@polkadot/util": "2.6.2",
|
||||
"@polkadot/wasm-crypto": "^1.2.1",
|
||||
"base-x": "^3.0.8",
|
||||
"bip39": "^3.0.2",
|
||||
"blakejs": "^1.1.0",
|
||||
"bn.js": "^5.1.1",
|
||||
"bs58": "^4.0.1",
|
||||
"elliptic": "^6.5.2",
|
||||
"js-sha3": "^0.8.0",
|
||||
"tweetnacl": "^1.0.2",
|
||||
"pbkdf2": "^3.0.17",
|
||||
"tweetnacl": "^1.0.3",
|
||||
"xxhashjs": "^0.2.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bn.js": "^4.11.6",
|
||||
"@types/bs58": "^4.0.1",
|
||||
"@types/elliptic": "^6.4.12",
|
||||
"@types/pbkdf2": "^3.0.0",
|
||||
"@types/xxhashjs": "^0.2.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,8 @@ import { Prefix } from './types';
|
||||
|
||||
import bs58 from 'bs58';
|
||||
|
||||
import checkChecksum from './checkChecksum';
|
||||
import defaults from './defaults';
|
||||
import sshash from './sshash';
|
||||
|
||||
export default function check (address: string, prefix: Prefix): [boolean, string | null] {
|
||||
const decoded = bs58.decode(address);
|
||||
@@ -18,18 +18,7 @@ export default function check (address: string, prefix: Prefix): [boolean, strin
|
||||
return [false, 'Invalid decoded address length'];
|
||||
}
|
||||
|
||||
const isPublicKey = decoded.length === 35;
|
||||
const [isValid] = checkChecksum(decoded);
|
||||
|
||||
// non-publicKeys has 1 byte checksums, else default to 2
|
||||
const endPos = decoded.length - (isPublicKey ? 2 : 1);
|
||||
|
||||
// calculate the hash and do the checksum byte checks
|
||||
const hash = sshash(decoded.subarray(0, endPos));
|
||||
const checks = isPublicKey
|
||||
? decoded[decoded.length - 2] === hash[0] && decoded[decoded.length - 1] === hash[1]
|
||||
: decoded[decoded.length - 1] === hash[0];
|
||||
|
||||
return !checks
|
||||
? [false, 'Invalid decoded address checksum']
|
||||
: [true, null];
|
||||
return [isValid, isValid ? null : 'Invalid decoded address checksum'];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// 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 sshash from './sshash';
|
||||
|
||||
export default function checkChecksum (decoded: Uint8Array): [boolean, number] {
|
||||
const isPublicKey = decoded.length === 35;
|
||||
|
||||
// non-publicKeys has 1 byte checksums, else default to 2
|
||||
const length = decoded.length - (isPublicKey ? 2 : 1);
|
||||
|
||||
// calculate the hash and do the checksum byte checks
|
||||
const hash = sshash(decoded.subarray(0, length));
|
||||
|
||||
// see if the hash actually matches
|
||||
const isValid = isPublicKey
|
||||
? decoded[decoded.length - 2] === hash[0] && decoded[decoded.length - 1] === hash[1]
|
||||
: decoded[decoded.length - 1] === hash[0];
|
||||
|
||||
return [isValid, length];
|
||||
}
|
||||
@@ -9,8 +9,8 @@ import { Prefix } from './types';
|
||||
import bs58 from 'bs58';
|
||||
import { assert, bufferToU8a, isHex, isU8a, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import checkChecksum from './checkChecksum';
|
||||
import defaults from './defaults';
|
||||
import sshash from './sshash';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
export default function decode (encoded: string | Uint8Array, ignoreChecksum?: boolean, ss58Format: Prefix = 99): Uint8Array {
|
||||
@@ -30,18 +30,9 @@ export default function decode (encoded: string | Uint8Array, ignoreChecksum?: b
|
||||
// console.log(`WARN: Expected ${prefix}, found ${decoded[0]}`);
|
||||
// }
|
||||
|
||||
const isPublicKey = decoded.length === 35;
|
||||
const [isValid, endPos] = checkChecksum(decoded);
|
||||
|
||||
// non-publicKeys has 1 byte checksums, else default to 2
|
||||
const endPos = decoded.length - (isPublicKey ? 2 : 1);
|
||||
|
||||
// calculate the hash and do the checksum byte checks
|
||||
const hash = sshash(decoded.subarray(0, endPos));
|
||||
const checks = isPublicKey
|
||||
? decoded[decoded.length - 2] === hash[0] && decoded[decoded.length - 1] === hash[1]
|
||||
: decoded[decoded.length - 1] === hash[0];
|
||||
|
||||
assert(ignoreChecksum || checks, error('Invalid decoded address checksum'));
|
||||
assert(ignoreChecksum || isValid, error('Invalid decoded address checksum'));
|
||||
|
||||
return decoded.slice(1, endPos);
|
||||
}
|
||||
|
||||
@@ -3,12 +3,14 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import checkAddress from './check';
|
||||
import checkAddressChecksum from './checkChecksum';
|
||||
import decodeAddress from './decode';
|
||||
import encodeAddress from './encode';
|
||||
import setSS58Format from './setSS58Format';
|
||||
|
||||
export {
|
||||
checkAddress,
|
||||
checkAddressChecksum,
|
||||
decodeAddress,
|
||||
encodeAddress,
|
||||
setSS58Format
|
||||
|
||||
@@ -6,6 +6,10 @@ import { Prefix } from './types';
|
||||
|
||||
import defaults from './defaults';
|
||||
|
||||
/**
|
||||
* @description Sets the global SS58 format to use for address encoding
|
||||
* @deprecated Use keyring.setSS58Format
|
||||
*/
|
||||
export default function setSS58Format (prefix: Prefix): void {
|
||||
defaults.prefix = prefix;
|
||||
}
|
||||
|
||||
@@ -2,10 +2,13 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
// polyfills
|
||||
import './polyfill';
|
||||
|
||||
import wasmCrypto from '@polkadot/wasm-crypto';
|
||||
// out of order and early in the chain, this also kicks off initialization on require
|
||||
export * from './init';
|
||||
|
||||
// all internal exports
|
||||
export * from './address';
|
||||
export * from './blake2';
|
||||
export * from './keccak';
|
||||
@@ -16,20 +19,5 @@ export * from './random';
|
||||
export * from './schnorrkel';
|
||||
export * from './secp256k1';
|
||||
export * from './sha512';
|
||||
export * from './signature';
|
||||
export * from './xxhash';
|
||||
|
||||
export function cryptoWaitReady (): Promise<boolean> {
|
||||
return wasmCrypto
|
||||
.waitReady()
|
||||
.then((): boolean => true)
|
||||
.catch((error): boolean => {
|
||||
console.error('Unable to initialize @polkadot/util-crypto', error);
|
||||
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
// start init process immediately
|
||||
cryptoWaitReady().catch((): void => {
|
||||
// shouldn't happen, logged above
|
||||
});
|
||||
|
||||
@@ -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 wasmCrypto from '@polkadot/wasm-crypto';
|
||||
|
||||
export function cryptoIsReady (): boolean {
|
||||
return wasmCrypto.isReady();
|
||||
}
|
||||
|
||||
export function cryptoWaitReady (): Promise<boolean> {
|
||||
return wasmCrypto
|
||||
.waitReady()
|
||||
.then((): boolean => true)
|
||||
.catch((error): boolean => {
|
||||
console.error('Unable to initialize @polkadot/util-crypto', error);
|
||||
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
// start init process immediately
|
||||
cryptoWaitReady().catch((): void => {
|
||||
// shouldn't happen, logged above
|
||||
});
|
||||
@@ -16,9 +16,9 @@ const BN_OPTIONS = {
|
||||
};
|
||||
|
||||
export default class DeriveJunction {
|
||||
private _chainCode: Uint8Array = new Uint8Array(32);
|
||||
readonly #chainCode: Uint8Array = new Uint8Array(32);
|
||||
|
||||
private _isHard = false;
|
||||
#isHard = false;
|
||||
|
||||
public static from (value: string): DeriveJunction {
|
||||
const [code, isHard] = value.startsWith('/')
|
||||
@@ -38,15 +38,15 @@ export default class DeriveJunction {
|
||||
}
|
||||
|
||||
public get chainCode (): Uint8Array {
|
||||
return this._chainCode;
|
||||
return this.#chainCode;
|
||||
}
|
||||
|
||||
public get isHard (): boolean {
|
||||
return this._isHard;
|
||||
return this.#isHard;
|
||||
}
|
||||
|
||||
public get isSoft (): boolean {
|
||||
return !this._isHard;
|
||||
return !this.#isHard;
|
||||
}
|
||||
|
||||
public hard (value: number | BN | string | Uint8Array): DeriveJunction {
|
||||
@@ -54,7 +54,7 @@ export default class DeriveJunction {
|
||||
}
|
||||
|
||||
public harden (): DeriveJunction {
|
||||
this._isHard = true;
|
||||
this.#isHard = true;
|
||||
|
||||
return this;
|
||||
}
|
||||
@@ -72,14 +72,14 @@ export default class DeriveJunction {
|
||||
return this.soft(blake2AsU8a(value));
|
||||
}
|
||||
|
||||
this._chainCode.fill(0);
|
||||
this._chainCode.set(value, 0);
|
||||
this.#chainCode.fill(0);
|
||||
this.#chainCode.set(value, 0);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public soften (): DeriveJunction {
|
||||
this._isHard = false;
|
||||
this.#isHard = false;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -6,37 +6,32 @@ import keyExtractPath, { ExtractResult } from './extractPath';
|
||||
|
||||
describe('keyExtractPath', (): void => {
|
||||
it('extracts properly from soft', (): void => {
|
||||
expect(
|
||||
keyExtractPath('/1')
|
||||
).toEqual({
|
||||
parts: ['/1'],
|
||||
path: [
|
||||
{ _isHard: false, _chainCode: Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }
|
||||
]
|
||||
});
|
||||
const test = keyExtractPath('/1');
|
||||
|
||||
expect(test.parts).toEqual(['/1']);
|
||||
expect(test.path.length).toEqual(1);
|
||||
expect(test.path[0].isHard).toEqual(false);
|
||||
expect(test.path[0].chainCode).toEqual(Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
|
||||
});
|
||||
|
||||
it('extracts properly from hard', (): void => {
|
||||
expect(
|
||||
keyExtractPath('//1')
|
||||
).toEqual({
|
||||
parts: ['//1'],
|
||||
path: [
|
||||
{ _isHard: true, _chainCode: Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }
|
||||
]
|
||||
});
|
||||
const test = keyExtractPath('//1');
|
||||
|
||||
expect(test.parts).toEqual(['//1']);
|
||||
expect(test.path.length).toEqual(1);
|
||||
expect(test.path[0].isHard).toEqual(true);
|
||||
expect(test.path[0].chainCode).toEqual(Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
|
||||
});
|
||||
|
||||
it('extracts properly from hard/soft', (): void => {
|
||||
expect(
|
||||
keyExtractPath('//1/2')
|
||||
).toEqual({
|
||||
parts: ['//1', '/2'],
|
||||
path: [
|
||||
{ _isHard: true, _chainCode: Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) },
|
||||
{ _isHard: false, _chainCode: Uint8Array.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }
|
||||
]
|
||||
});
|
||||
const test = keyExtractPath('//1/2');
|
||||
|
||||
expect(test.parts).toEqual(['//1', '/2']);
|
||||
expect(test.path.length).toEqual(2);
|
||||
expect(test.path[0].isHard).toEqual(true);
|
||||
expect(test.path[0].chainCode).toEqual(Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
|
||||
expect(test.path[1].isHard).toEqual(false);
|
||||
expect(test.path[1].chainCode).toEqual(Uint8Array.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
|
||||
});
|
||||
|
||||
it('does not extract from invalid paths', (): void => {
|
||||
|
||||
@@ -12,126 +12,115 @@ describe('keyExtractSuri', (): void => {
|
||||
});
|
||||
|
||||
it('derives on "hello world"', (): void => {
|
||||
expect(
|
||||
keyExtractSuri('hello world')
|
||||
).toEqual({
|
||||
path: [],
|
||||
phrase: 'hello world'
|
||||
});
|
||||
const test = keyExtractSuri('hello world');
|
||||
|
||||
expect(test.phrase).toEqual('hello world');
|
||||
expect(test.path.length).toEqual(0);
|
||||
});
|
||||
|
||||
it('derives on "hello world/1', (): void => {
|
||||
expect(
|
||||
keyExtractSuri('hello world/1')
|
||||
).toEqual({
|
||||
path: [
|
||||
{ _isHard: false, _chainCode: Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }
|
||||
],
|
||||
phrase: 'hello world'
|
||||
});
|
||||
const test = keyExtractSuri('hello world/1');
|
||||
|
||||
expect(test.password).not.toBeDefined();
|
||||
expect(test.phrase).toEqual('hello world');
|
||||
expect(test.path.length).toEqual(1);
|
||||
expect(test.path[0].isHard).toEqual(false);
|
||||
expect(test.path[0].chainCode).toEqual(Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
|
||||
});
|
||||
|
||||
it('derives on "hello world/DOT', (): void => {
|
||||
expect(
|
||||
keyExtractSuri('hello world/DOT')
|
||||
).toEqual({
|
||||
path: [
|
||||
{ _isHard: false, _chainCode: Uint8Array.from([12, 68, 79, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }
|
||||
],
|
||||
phrase: 'hello world'
|
||||
});
|
||||
const test = keyExtractSuri('hello world/DOT');
|
||||
|
||||
expect(test.password).not.toBeDefined();
|
||||
expect(test.phrase).toEqual('hello world');
|
||||
expect(test.path.length).toEqual(1);
|
||||
expect(test.path[0].isHard).toEqual(false);
|
||||
expect(test.path[0].chainCode).toEqual(Uint8Array.from([12, 68, 79, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
|
||||
});
|
||||
|
||||
it('derives on "hello world//1', (): void => {
|
||||
expect(
|
||||
keyExtractSuri('hello world//1')
|
||||
).toEqual({
|
||||
path: [
|
||||
{ _isHard: true, _chainCode: Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }
|
||||
],
|
||||
phrase: 'hello world'
|
||||
});
|
||||
const test = keyExtractSuri('hello world//1');
|
||||
|
||||
expect(test.password).not.toBeDefined();
|
||||
expect(test.phrase).toEqual('hello world');
|
||||
expect(test.path.length).toEqual(1);
|
||||
expect(test.path[0].isHard).toEqual(true);
|
||||
expect(test.path[0].chainCode).toEqual(Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
|
||||
});
|
||||
|
||||
it('derives on "hello world//DOT', (): void => {
|
||||
expect(
|
||||
keyExtractSuri('hello world//DOT')
|
||||
).toEqual({
|
||||
path: [
|
||||
{ _isHard: true, _chainCode: Uint8Array.from([12, 68, 79, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }
|
||||
],
|
||||
phrase: 'hello world'
|
||||
});
|
||||
const test = keyExtractSuri('hello world//DOT');
|
||||
|
||||
expect(test.password).not.toBeDefined();
|
||||
expect(test.phrase).toEqual('hello world');
|
||||
expect(test.path.length).toEqual(1);
|
||||
expect(test.path[0].isHard).toEqual(true);
|
||||
expect(test.path[0].chainCode).toEqual(Uint8Array.from([12, 68, 79, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
|
||||
});
|
||||
|
||||
it('derives on "hello world//1/DOT', (): void => {
|
||||
expect(
|
||||
keyExtractSuri('hello world//1/DOT')
|
||||
).toEqual({
|
||||
path: [
|
||||
{ _isHard: true, _chainCode: Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) },
|
||||
{ _isHard: false, _chainCode: Uint8Array.from([12, 68, 79, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }
|
||||
],
|
||||
phrase: 'hello world'
|
||||
});
|
||||
const test = keyExtractSuri('hello world//1/DOT');
|
||||
|
||||
expect(test.password).not.toBeDefined();
|
||||
expect(test.phrase).toEqual('hello world');
|
||||
expect(test.path.length).toEqual(2);
|
||||
expect(test.path[0].isHard).toEqual(true);
|
||||
expect(test.path[0].chainCode).toEqual(Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
|
||||
expect(test.path[1].isHard).toEqual(false);
|
||||
expect(test.path[1].chainCode).toEqual(Uint8Array.from([12, 68, 79, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
|
||||
});
|
||||
|
||||
it('derives on "hello world//DOT/1', (): void => {
|
||||
expect(
|
||||
keyExtractSuri('hello world//DOT/1')
|
||||
).toEqual({
|
||||
path: [
|
||||
{ _isHard: true, _chainCode: Uint8Array.from([12, 68, 79, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) },
|
||||
{ _isHard: false, _chainCode: Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }
|
||||
],
|
||||
phrase: 'hello world'
|
||||
});
|
||||
const test = keyExtractSuri('hello world//DOT/1');
|
||||
|
||||
expect(test.password).not.toBeDefined();
|
||||
expect(test.phrase).toEqual('hello world');
|
||||
expect(test.path.length).toEqual(2);
|
||||
expect(test.path[0].isHard).toEqual(true);
|
||||
expect(test.path[0].chainCode).toEqual(Uint8Array.from([12, 68, 79, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
|
||||
expect(test.path[1].isHard).toEqual(false);
|
||||
expect(test.path[1].chainCode).toEqual(Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
|
||||
});
|
||||
|
||||
it('derives on "hello world///password"', (): void => {
|
||||
expect(
|
||||
keyExtractSuri('hello world///password')
|
||||
).toEqual({
|
||||
password: 'password',
|
||||
path: [],
|
||||
phrase: 'hello world'
|
||||
});
|
||||
const test = keyExtractSuri('hello world///password');
|
||||
|
||||
expect(test.password).toEqual('password');
|
||||
expect(test.phrase).toEqual('hello world');
|
||||
expect(test.path.length).toEqual(0);
|
||||
});
|
||||
|
||||
it('derives on "hello world//1/DOT///password"', (): void => {
|
||||
expect(
|
||||
keyExtractSuri('hello world//1/DOT///password')
|
||||
).toEqual({
|
||||
path: [
|
||||
{ _isHard: true, _chainCode: Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) },
|
||||
{ _isHard: false, _chainCode: Uint8Array.from([12, 68, 79, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }
|
||||
],
|
||||
password: 'password',
|
||||
phrase: 'hello world'
|
||||
});
|
||||
const test = keyExtractSuri('hello world//1/DOT///password');
|
||||
|
||||
expect(test.password).toEqual('password');
|
||||
expect(test.phrase).toEqual('hello world');
|
||||
expect(test.path.length).toEqual(2);
|
||||
expect(test.path[0].isHard).toEqual(true);
|
||||
expect(test.path[0].chainCode).toEqual(Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
|
||||
expect(test.path[1].isHard).toEqual(false);
|
||||
expect(test.path[1].chainCode).toEqual(Uint8Array.from([12, 68, 79, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
|
||||
});
|
||||
|
||||
it('derives on "hello world/1//DOT///password"', (): void => {
|
||||
expect(
|
||||
keyExtractSuri('hello world/1//DOT///password')
|
||||
).toEqual({
|
||||
path: [
|
||||
{ _isHard: false, _chainCode: Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) },
|
||||
{ _isHard: true, _chainCode: Uint8Array.from([12, 68, 79, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }
|
||||
],
|
||||
password: 'password',
|
||||
phrase: 'hello world'
|
||||
});
|
||||
const test = keyExtractSuri('hello world/1//DOT///password');
|
||||
|
||||
expect(test.password).toEqual('password');
|
||||
expect(test.phrase).toEqual('hello world');
|
||||
expect(test.path.length).toEqual(2);
|
||||
expect(test.path[0].isHard).toEqual(false);
|
||||
expect(test.path[0].chainCode).toEqual(Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
|
||||
expect(test.path[1].isHard).toEqual(true);
|
||||
expect(test.path[1].chainCode).toEqual(Uint8Array.from([12, 68, 79, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
|
||||
});
|
||||
|
||||
it('derives on actual Alice', (): void => {
|
||||
expect(
|
||||
keyExtractSuri('bottom drive obey lake curtain smoke basket hold race lonely fit walk//Alice')
|
||||
).toEqual({
|
||||
path: [
|
||||
{ _isHard: true, _chainCode: Uint8Array.from([20, 65, 108, 105, 99, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }
|
||||
],
|
||||
phrase: 'bottom drive obey lake curtain smoke basket hold race lonely fit walk'
|
||||
});
|
||||
const test = keyExtractSuri('bottom drive obey lake curtain smoke basket hold race lonely fit walk//Alice');
|
||||
|
||||
expect(test.password).not.toBeDefined();
|
||||
expect(test.phrase).toEqual('bottom drive obey lake curtain smoke basket hold race lonely fit walk');
|
||||
expect(test.path.length).toEqual(1);
|
||||
expect(test.path[0].isHard).toEqual(true);
|
||||
expect(test.path[0].chainCode).toEqual(Uint8Array.from([20, 65, 108, 105, 99, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
// 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.
|
||||
|
||||
/**
|
||||
* @summary Utilities for working with signatures
|
||||
*/
|
||||
|
||||
export { default as signatureVerify } from './verify';
|
||||
@@ -0,0 +1,92 @@
|
||||
// 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 { hexToU8a, stringToU8a, u8aConcat, u8aToHex } from '@polkadot/util';
|
||||
import { waitReady } from '@polkadot/wasm-crypto';
|
||||
|
||||
import { decodeAddress } from '../address';
|
||||
import { signatureVerify } from '.';
|
||||
|
||||
const ADDR_ED = 'DxN4uvzwPzJLtn17yew6jEffPhXQfdKHTp2brufb98vGbPN';
|
||||
const ADDR_SR = 'EK1bFgKm2FsghcttHT7TB7rNyXApFgs9fCbijMGQNyFGBQm';
|
||||
const MESSAGE = 'hello world';
|
||||
const SIG_ED = '0x299d3bf4c8bb51af732f8067b3a3015c0862a5ff34721749d8ed6577ea2708365d1c5f76bd519009971e41156f12c70abc2533837ceb3bad9a05a99ab923de06';
|
||||
const SIG_SR = '0xca01419b5a17219f7b78335658cab3b126db523a5df7be4bfc2bef76c2eb3b1dcf4ca86eb877d0a6cf6df12db5995c51d13b00e005d053b892bd09c594434288';
|
||||
const MUL_ED = u8aToHex(u8aConcat(new Uint8Array([0]), hexToU8a(SIG_ED)));
|
||||
const MUL_SR = u8aToHex(u8aConcat(new Uint8Array([1]), hexToU8a(SIG_SR)));
|
||||
|
||||
describe('signatureVerify', (): void => {
|
||||
beforeEach(async (): Promise<void> => {
|
||||
await waitReady();
|
||||
});
|
||||
|
||||
it('throws on invalid signature length', (): void => {
|
||||
expect(
|
||||
() => signatureVerify(MESSAGE, new Uint8Array(32), ADDR_ED)
|
||||
).toThrow('Invalid signature length, expected 64 or 65 bytes, found 32');
|
||||
});
|
||||
|
||||
describe('verifyDetect', (): void => {
|
||||
it('verifies an ed25519 signature', (): void => {
|
||||
expect(signatureVerify(MESSAGE, SIG_ED, ADDR_ED)).toEqual({
|
||||
crypto: 'ed25519',
|
||||
isValid: true
|
||||
});
|
||||
});
|
||||
|
||||
it('verifies an sr25519 signature', (): void => {
|
||||
expect(signatureVerify(MESSAGE, SIG_SR, ADDR_SR)).toEqual({
|
||||
crypto: 'sr25519',
|
||||
isValid: true
|
||||
});
|
||||
});
|
||||
|
||||
it('allows various inputs', (): void => {
|
||||
expect(signatureVerify(stringToU8a(MESSAGE), hexToU8a(SIG_ED), decodeAddress(ADDR_ED))).toEqual({
|
||||
crypto: 'ed25519',
|
||||
isValid: true
|
||||
});
|
||||
});
|
||||
|
||||
it('fails on an invalid signature', (): void => {
|
||||
expect(signatureVerify(MESSAGE, SIG_SR, ADDR_ED)).toEqual({
|
||||
crypto: 'none',
|
||||
isValid: false
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('verifyMultisig', (): void => {
|
||||
it('throws with invalid multisig indicator', (): void => {
|
||||
const u8aSig = hexToU8a(MUL_ED);
|
||||
|
||||
u8aSig[0] = 69;
|
||||
|
||||
expect(
|
||||
() => signatureVerify(MESSAGE, u8aSig, ADDR_ED)
|
||||
).toThrow('Unknown crypto type, expected signature prefix of 0 or 1, found 69');
|
||||
});
|
||||
|
||||
it('verifies an ed25519 signature', (): void => {
|
||||
expect(signatureVerify(MESSAGE, MUL_ED, ADDR_ED)).toEqual({
|
||||
crypto: 'ed25519',
|
||||
isValid: true
|
||||
});
|
||||
});
|
||||
|
||||
it('verifies an sr25519 signature', (): void => {
|
||||
expect(signatureVerify(MESSAGE, MUL_SR, ADDR_SR)).toEqual({
|
||||
crypto: 'sr25519',
|
||||
isValid: true
|
||||
});
|
||||
});
|
||||
|
||||
it('fails on an invalid signature', (): void => {
|
||||
expect(signatureVerify(MESSAGE, MUL_SR, ADDR_ED)).toEqual({
|
||||
crypto: 'sr25519',
|
||||
isValid: false
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
// 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 { KeypairType, VerifyResult } from '../types';
|
||||
|
||||
import { assert, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import addressDecode from '../address/decode';
|
||||
import naclVerify from '../nacl/verify';
|
||||
import schnorrkelVerify from '../schnorrkel/verify';
|
||||
|
||||
const VERIFIERS: [KeypairType, (message: Uint8Array | string, signature: Uint8Array | string, publicKey: Uint8Array | string) => boolean][] = [
|
||||
['ed25519', naclVerify],
|
||||
['sr25519', schnorrkelVerify]
|
||||
];
|
||||
|
||||
function verifyDetect (result: VerifyResult, message: Uint8Array | string, signature: Uint8Array, publicKey: Uint8Array): VerifyResult {
|
||||
result.isValid = VERIFIERS.some(([crypto, verify]): boolean => {
|
||||
try {
|
||||
if (verify(message, signature, publicKey)) {
|
||||
result.crypto = crypto;
|
||||
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
// do nothing, result.isValid still set to false
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function verifyMultisig (result: VerifyResult, message: Uint8Array | string, signature: Uint8Array, publicKey: Uint8Array): VerifyResult {
|
||||
assert([0, 1].includes(signature[0]), `Unknown crypto type, expected signature prefix of 0 or 1, found ${signature[0]}`);
|
||||
|
||||
const isEd25519 = signature[0] === 0;
|
||||
|
||||
result.crypto = isEd25519
|
||||
? 'ed25519'
|
||||
: 'sr25519';
|
||||
|
||||
try {
|
||||
result.isValid = isEd25519
|
||||
? naclVerify(message, signature.subarray(1), publicKey)
|
||||
: schnorrkelVerify(message, signature.subarray(1), publicKey);
|
||||
} catch (error) {
|
||||
// ignore, result.isValid still set to false
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export default function signatureVerify (message: Uint8Array | string, signature: Uint8Array | string, addressOrPublicKey: Uint8Array | string): VerifyResult {
|
||||
const signatureU8a = u8aToU8a(signature);
|
||||
|
||||
assert([64, 65].includes(signatureU8a.length), `Invalid signature length, expected 64 or 65 bytes, found ${signatureU8a.length}`);
|
||||
|
||||
const result: VerifyResult = { crypto: 'none', isValid: false };
|
||||
const publicKey = addressDecode(addressOrPublicKey);
|
||||
|
||||
return signatureU8a.length === 65
|
||||
? verifyMultisig(result, message, signatureU8a, publicKey)
|
||||
: verifyDetect(result, message, signatureU8a, publicKey);
|
||||
}
|
||||
@@ -13,3 +13,8 @@ export interface Seedpair {
|
||||
}
|
||||
|
||||
export type KeypairType = 'ed25519' | 'sr25519';
|
||||
|
||||
export interface VerifyResult {
|
||||
crypto: 'none' | KeypairType;
|
||||
isValid: boolean;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/util",
|
||||
"version": "2.2.1",
|
||||
"version": "2.6.2",
|
||||
"description": "A collection of useful utilities for @polkadot",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -25,12 +25,11 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.8.3",
|
||||
"@babel/runtime": "^7.8.7",
|
||||
"@types/bn.js": "^4.11.6",
|
||||
"bn.js": "^5.1.1",
|
||||
"camelcase": "^5.3.1",
|
||||
"chalk": "^3.0.0",
|
||||
"ip-regex": "^4.1.0",
|
||||
"moment": "^2.24.0"
|
||||
"ip-regex": "^4.1.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,8 +22,7 @@ type MessageFn = () => string;
|
||||
* assert(false, () => 'message'); // Error with 'message'
|
||||
* ```
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export default function assert (condition: any, message: string | MessageFn): asserts condition {
|
||||
export default function assert (condition: boolean | object | string | number | undefined | null, message: string | MessageFn): asserts condition {
|
||||
if (!condition) {
|
||||
throw new Error(
|
||||
isFunction(message)
|
||||
|
||||
@@ -19,6 +19,12 @@ describe('bnToBn', (): void => {
|
||||
).toEqual(128);
|
||||
});
|
||||
|
||||
it('converts BigInt values to BN', (): void => {
|
||||
expect(
|
||||
bnToBn(128_821n).toNumber()
|
||||
).toEqual(128821);
|
||||
});
|
||||
|
||||
it('converts number values to BN', (): void => {
|
||||
expect(
|
||||
bnToBn(128).toNumber()
|
||||
|
||||
@@ -6,15 +6,16 @@ import { ToBn } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
|
||||
import isBigInt from '../is/bigInt';
|
||||
import isToBn from '../is/toBn';
|
||||
import isHex from '../is/hex';
|
||||
import hexToBn from '../hex/toBn';
|
||||
|
||||
/**
|
||||
* @name bnToBn
|
||||
* @summary Creates a BN value from a BN.js bignumber or number input.
|
||||
* @summary Creates a BN value from a BN, BigInt, string (base 10 or hex) or number input.
|
||||
* @description
|
||||
* `null` inputs returns a `0x0` result, BN values returns the value, numnbers returns a BN representation.
|
||||
* `null` inputs returns a `0x0` result, BN values returns the value, numbers returns a BN representation.
|
||||
* @example
|
||||
* <BR>
|
||||
*
|
||||
@@ -26,11 +27,13 @@ import hexToBn from '../hex/toBn';
|
||||
* bnToBn(new BN(0x1234)); // => BN(0x1234)
|
||||
* ```
|
||||
*/
|
||||
export default function bnToBn <ExtToBn extends ToBn> (value?: ExtToBn | BN | string | number | null): BN {
|
||||
export default function bnToBn <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | string | number | null): BN {
|
||||
if (!value) {
|
||||
return new BN(0);
|
||||
} else if (isHex(value)) {
|
||||
return hexToBn(value.toString());
|
||||
} else if (isBigInt(value)) {
|
||||
return new BN(value.toString());
|
||||
}
|
||||
|
||||
return BN.isBN(value)
|
||||
|
||||
@@ -30,10 +30,7 @@ interface Options extends ToBnOptions {
|
||||
* bnToHex(new BN(0x123456)); // => '0x123456'
|
||||
* ```
|
||||
*/
|
||||
export default function bnToHex (
|
||||
value?: BN | number | null,
|
||||
options: number | Options = { bitLength: -1, isLe: false, isNegative: false }
|
||||
): string {
|
||||
export default function bnToHex (value?: BN | BigInt | number | null, options: number | Options = { bitLength: -1, isLe: false, isNegative: false }): string {
|
||||
if (!value) {
|
||||
return ZERO_STR;
|
||||
}
|
||||
|
||||
@@ -26,13 +26,9 @@ interface Options extends ToBnOptions {
|
||||
* bnToU8a(new BN(0x1234)); // => [0x12, 0x34]
|
||||
* ```
|
||||
*/
|
||||
function bnToU8a (value: BN | number | null, options?: Options): Uint8Array;
|
||||
function bnToU8a (value: BN | number | null, bitLength?: number, isLe?: boolean): Uint8Array;
|
||||
function bnToU8a (
|
||||
value: BN | number | null,
|
||||
arg1: number | Options = { bitLength: -1, isLe: true, isNegative: false },
|
||||
arg2?: boolean
|
||||
): Uint8Array {
|
||||
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 {
|
||||
const _options: Options = {
|
||||
isLe: true,
|
||||
isNegative: false,
|
||||
|
||||
@@ -24,7 +24,7 @@ const MAX_U32 = new BN(2).pow(new BN(32 - 2)).subn(1);
|
||||
* console.log(compactToU8a(511, 32)); // Uint8Array([0b11111101, 0b00000111])
|
||||
* ```
|
||||
*/
|
||||
export default function compactToU8a (_value: BN | number): Uint8Array {
|
||||
export default function compactToU8a (_value: BN | BigInt | number): Uint8Array {
|
||||
const value = bnToBn(_value);
|
||||
|
||||
if (value.lte(MAX_U8)) {
|
||||
|
||||
@@ -26,7 +26,7 @@ type PjsGlobal = NodeJS.Global & PjsChecks;
|
||||
type PjsWindow = Window & PjsChecks;
|
||||
|
||||
function expandPath (path?: string): string {
|
||||
return (!path || path.length < 5) ? '<unknown path>' : path;
|
||||
return (!path || path.length < 5) ? '<unknown>' : path;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
@@ -47,7 +47,7 @@ function flattenVersions (_all: (VersionPath | string)[]): string {
|
||||
* @name detectPackage
|
||||
* @summary Checks that a specific package is only imported once
|
||||
*/
|
||||
export default function detectPackage ({ name, version }: PackageJson, path?: string): void {
|
||||
export default function detectPackage ({ name, version }: PackageJson, path?: string | false): void {
|
||||
const _global = typeof window !== 'undefined'
|
||||
? window as PjsWindow
|
||||
: global as PjsGlobal;
|
||||
@@ -58,7 +58,7 @@ export default function detectPackage ({ name, version }: PackageJson, path?: st
|
||||
|
||||
assert(name.startsWith('@polkadot'), `Invalid package descriptor ${name}`);
|
||||
|
||||
_global.__polkadotjs[name] = [...(_global.__polkadotjs[name] || []), { path, version }];
|
||||
_global.__polkadotjs[name] = [...(_global.__polkadotjs[name] || []), { path: path || '', version }];
|
||||
|
||||
if (_global.__polkadotjs[name].length !== 1) {
|
||||
const versions = flattenVersions(_global.__polkadotjs[name]);
|
||||
|
||||
@@ -16,14 +16,26 @@ describe('formatBalance', (): void => {
|
||||
});
|
||||
|
||||
it('formats 123,456,789,000 (decimals=15)', (): void => {
|
||||
expect(
|
||||
formatBalance(TESTVAL, { withSi: true, decimals: 15 })
|
||||
).toEqual('123.456µ Unit');
|
||||
});
|
||||
|
||||
it('formats BigInt numbers', (): void => {
|
||||
expect(
|
||||
formatBalance(123_456_789_000n, { withSi: true, decimals: 15 })
|
||||
).toEqual('123.456µ Unit');
|
||||
});
|
||||
|
||||
it('formats 123,456,789,000 (decimals=15, old style)', (): void => {
|
||||
expect(
|
||||
formatBalance(TESTVAL, { withSi: true }, 15)
|
||||
).toEqual('123.456µ Unit');
|
||||
});
|
||||
|
||||
it('formats 123,456,789,000 (decimals=36)', (): void => {
|
||||
it('formats 123,456,789,000 (decimals=36, option)', (): void => {
|
||||
expect(
|
||||
formatBalance(TESTVAL, { withSi: true }, 36)
|
||||
formatBalance(TESTVAL, { withSi: true, decimals: 36 })
|
||||
).toEqual('0.123y Unit');
|
||||
});
|
||||
|
||||
@@ -34,13 +46,13 @@ describe('formatBalance', (): void => {
|
||||
something: 'else'
|
||||
};
|
||||
expect(
|
||||
formatBalance(compact, { withSi: true }, 15)
|
||||
formatBalance(compact, { withSi: true, decimals: 15 })
|
||||
).toEqual('123.456µ Unit');
|
||||
});
|
||||
|
||||
it('formats 123,456,789,000 (decimals=12)', (): void => {
|
||||
expect(
|
||||
formatBalance(TESTVAL, { withSi: true }, 12)
|
||||
formatBalance(TESTVAL, { withSi: true, decimals: 12 })
|
||||
).toEqual('123.456m Unit');
|
||||
});
|
||||
|
||||
@@ -50,6 +62,18 @@ describe('formatBalance', (): void => {
|
||||
).toEqual('123.456 Unit');
|
||||
});
|
||||
|
||||
it('formats 123,456,789,000 (decimals=9, no unit)', (): void => {
|
||||
expect(
|
||||
formatBalance(TESTVAL, { withSi: true, withUnit: false }, 9)
|
||||
).toEqual('123.456');
|
||||
});
|
||||
|
||||
it('formats 123,456,789,000 (decimals=9, unit given)', (): void => {
|
||||
expect(
|
||||
formatBalance(TESTVAL, { withSi: true, withUnit: 'FOO' }, 9)
|
||||
).toEqual('123.456 FOO');
|
||||
});
|
||||
|
||||
it('formats 123,456,789,000 (decimals=12, no SI)', (): void => {
|
||||
expect(
|
||||
formatBalance(TESTVAL, { withSi: false }, 12)
|
||||
@@ -80,6 +104,12 @@ describe('formatBalance', (): void => {
|
||||
).toEqual('123.456k Unit');
|
||||
});
|
||||
|
||||
it('formats 123,456,789,000 (decimals=6, unit specified)', (): void => {
|
||||
expect(
|
||||
formatBalance(TESTVAL, { withSi: true, withUnit: 'BAR' }, 6)
|
||||
).toEqual('123.456k BAR');
|
||||
});
|
||||
|
||||
it('formats 123,456,789,000 * 10 (decimals=12)', (): void => {
|
||||
expect(
|
||||
formatBalance(TESTVAL.muln(10), { withSi: true }, 12)
|
||||
|
||||
@@ -18,14 +18,15 @@ interface Defaults {
|
||||
}
|
||||
|
||||
interface Options {
|
||||
decimals?: number;
|
||||
forceUnit?: string;
|
||||
withSi?: boolean;
|
||||
withSiFull?: boolean;
|
||||
withUnit?: boolean;
|
||||
withUnit?: boolean | string;
|
||||
}
|
||||
|
||||
interface BalanceFormatter {
|
||||
<ExtToBn extends ToBn> (input?: number | string | BN | ExtToBn, options?: Options, decimals?: number): string;
|
||||
<ExtToBn extends ToBn> (input?: number | string | BN | BigInt | ExtToBn, options?: Options, decimals?: number): string;
|
||||
calcSi (text: string, decimals?: number): SiDef;
|
||||
findSi (type: string): SiDef;
|
||||
getDefaults (): Defaults;
|
||||
@@ -40,7 +41,7 @@ let defaultDecimals = DEFAULT_DECIMALS;
|
||||
let defaultUnit = DEFAULT_UNIT;
|
||||
|
||||
// Formats a string/number with <prefix>.<postfix><type> notation
|
||||
function _formatBalance <ExtToBn extends ToBn> (input?: number | string | BN | ExtToBn, options: Options | boolean = true, decimals: number = defaultDecimals): string {
|
||||
function _formatBalance <ExtToBn extends ToBn> (input?: number | string | BN | BigInt | ExtToBn, options: Options | boolean = true, optDecimals: number = defaultDecimals): string {
|
||||
let text = bnToBn(input).toString();
|
||||
|
||||
if (text.length === 0 || text === '0') {
|
||||
@@ -56,7 +57,7 @@ function _formatBalance <ExtToBn extends ToBn> (input?: number | string | BN | E
|
||||
}
|
||||
|
||||
// extract options - the boolean case is for backwards-compat
|
||||
const { forceUnit = undefined, withSi = true, withSiFull = false, withUnit = true } = isBoolean(options)
|
||||
const { decimals = optDecimals, forceUnit = undefined, withSi = true, withSiFull = false, withUnit = true } = isBoolean(options)
|
||||
? { withSi: options }
|
||||
: options;
|
||||
|
||||
@@ -69,11 +70,11 @@ function _formatBalance <ExtToBn extends ToBn> (input?: number | string | BN | E
|
||||
const padding = mid < 0 ? 0 - mid : 0;
|
||||
const postfix = `${`${new Array(padding + 1).join('0')}${text}`.substr(mid < 0 ? 0 : mid)}000`.substr(0, 3);
|
||||
const units = withSi || withSiFull
|
||||
? (
|
||||
si.value === '-'
|
||||
? ` ${si.text}`
|
||||
: `${withSiFull ? ` ${si.text}` : si.value}${withUnit ? ` ${SI[SI_MID].text}` : ''}`
|
||||
)
|
||||
? si.value === '-'
|
||||
? withUnit
|
||||
? ` ${isBoolean(withUnit) ? si.text : withUnit}`
|
||||
: ''
|
||||
: `${withSiFull ? ` ${si.text}` : si.value}${withUnit ? ` ${isBoolean(withUnit) ? SI[SI_MID].text : withUnit}` : ''}`
|
||||
: '';
|
||||
|
||||
return `${isNegative ? '-' : ''}${formatDecimal(prefix || '0')}.${postfix}${units}`;
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
// 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 formatDate from './formatDate';
|
||||
|
||||
describe('formatDate', (): void => {
|
||||
it('formats a known date into the correct format', (): void => {
|
||||
const date = new Date(Date.UTC(2020, 1, 15, 11, 14, 34));
|
||||
|
||||
// make this test-locale agnostic
|
||||
date.setTime(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
|
||||
|
||||
expect(formatDate(date)).toEqual('2020-02-15 11:14:34');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
// 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.
|
||||
|
||||
/** @internal */
|
||||
function zeroPad (value: number): string {
|
||||
return value.toString().padStart(2, '0');
|
||||
}
|
||||
|
||||
export default function formatDate (date: Date): string {
|
||||
const year = date.getFullYear().toString();
|
||||
const month = zeroPad((date.getMonth() + 1));
|
||||
const day = zeroPad(date.getDate());
|
||||
const hour = zeroPad(date.getHours());
|
||||
const minute = zeroPad(date.getMinutes());
|
||||
const second = zeroPad(date.getSeconds());
|
||||
|
||||
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
|
||||
}
|
||||
@@ -25,6 +25,12 @@ describe('formatNumber', (): void => {
|
||||
).toEqual('12,345');
|
||||
});
|
||||
|
||||
it('formats BigInt numbers', (): void => {
|
||||
expect(
|
||||
formatNumber(123_456_789n)
|
||||
).toEqual('123,456,789');
|
||||
});
|
||||
|
||||
it('formats Compact<BN>', (): void => {
|
||||
expect(
|
||||
formatNumber({
|
||||
|
||||
@@ -9,6 +9,6 @@ import BN from 'bn.js';
|
||||
import bnToBn from '../bn/toBn';
|
||||
import formatDecimal from './formatDecimal';
|
||||
|
||||
export default function formatNumber <ExtToBn extends ToBn> (value?: ExtToBn | BN | number | null): string {
|
||||
export default function formatNumber <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null): string {
|
||||
return formatDecimal(bnToBn(value).toString());
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
export { default as formatBalance } from './formatBalance';
|
||||
export { default as formatDate } from './formatDate';
|
||||
export { default as formatDecimal } from './formatDecimal';
|
||||
export { default as formatElapsed } from './formatElapsed';
|
||||
export { default as formatNumber } from './formatNumber';
|
||||
|
||||
@@ -25,19 +25,11 @@ export default function hexFixLength (value: string, bitLength = -1, withPadding
|
||||
const strLength = Math.ceil(bitLength / 4);
|
||||
const hexLength = strLength + 2;
|
||||
|
||||
if (bitLength === -1 || value.length === hexLength || (!withPadding && value.length < hexLength)) {
|
||||
return hexAddPrefix(
|
||||
hexStripPrefix(value)
|
||||
);
|
||||
}
|
||||
|
||||
if (value.length > hexLength) {
|
||||
return hexAddPrefix(
|
||||
hexStripPrefix(value).slice(-1 * strLength)
|
||||
);
|
||||
}
|
||||
|
||||
return hexAddPrefix(
|
||||
`${'0'.repeat(strLength)}${hexStripPrefix(value)}`.slice(-1 * strLength)
|
||||
(bitLength === -1 || value.length === hexLength || (!withPadding && value.length < hexLength))
|
||||
? hexStripPrefix(value)
|
||||
: (value.length > hexLength)
|
||||
? hexStripPrefix(value).slice(-1 * strLength)
|
||||
: `${'0'.repeat(strLength)}${hexStripPrefix(value)}`.slice(-1 * strLength)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -19,9 +19,7 @@ import hexToBn from './toBn';
|
||||
* ```
|
||||
*/
|
||||
export default function hexToNumber (value?: string | null): number {
|
||||
if (!value) {
|
||||
return NaN;
|
||||
}
|
||||
|
||||
return hexToBn(value).toNumber();
|
||||
return value
|
||||
? hexToBn(value).toNumber()
|
||||
: NaN;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// 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 { isBigInt } from '.';
|
||||
|
||||
describe('isBigInt', (): void => {
|
||||
it('returns true when a BigInt value', (): void => {
|
||||
expect(
|
||||
isBigInt(123_456n)
|
||||
).toEqual(true);
|
||||
});
|
||||
|
||||
it('returns true when a BigInt value', (): void => {
|
||||
expect(
|
||||
isBigInt(BigInt(123_456))
|
||||
).toEqual(true);
|
||||
});
|
||||
|
||||
it('returns false on non-BigInt values', (): void => {
|
||||
expect(
|
||||
isBigInt(0)
|
||||
).toEqual(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
// 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.
|
||||
|
||||
/**
|
||||
* @name isBigInt
|
||||
* @summary Tests for a `BigInt` object instance.
|
||||
* @description
|
||||
* Checks to see if the input object is an instance of `BigInt`
|
||||
* @example
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import { isBigInt } from '@polkadot/util';
|
||||
*
|
||||
* console.log('isBigInt', isBigInt(123_456n)); // => true
|
||||
* ```
|
||||
*/
|
||||
export default function isBigInt (value: BigInt | object | string | number | undefined | null): value is BigInt {
|
||||
return typeof value === 'bigint';
|
||||
}
|
||||
@@ -19,7 +19,6 @@ import BN from 'bn.js';
|
||||
* console.log('isBn', isBn(new BN(1))); // => true
|
||||
* ```
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export default function isBn (value: any): value is BN {
|
||||
export default function isBn (value: object | string | number | undefined | null): value is BN {
|
||||
return BN.isBN(value);
|
||||
}
|
||||
|
||||
@@ -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 BN from 'bn.js';
|
||||
|
||||
import { isChildClass } from '.';
|
||||
|
||||
describe('isChildClass', (): void => {
|
||||
it('returns true when a Child value', (): void => {
|
||||
expect(
|
||||
isChildClass(BN, class Test extends BN {})
|
||||
).toEqual(true);
|
||||
});
|
||||
|
||||
it('returns false on non-Child values', (): void => {
|
||||
expect(
|
||||
isChildClass(BN, Uint8Array)
|
||||
).toEqual(false);
|
||||
});
|
||||
|
||||
it('returns false on undefined', (): void => {
|
||||
expect(
|
||||
isChildClass(BN)
|
||||
).toEqual(false);
|
||||
});
|
||||
|
||||
it('does TS magic, determining type', (): void => {
|
||||
const T = (class extends BN {}) as unknown;
|
||||
|
||||
if (isChildClass(BN, T)) {
|
||||
expect(new T(12345).toNumber()).toEqual(12345);
|
||||
} else {
|
||||
throw new Error('Not a child class');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
// 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 { Constructor } from '../types';
|
||||
|
||||
/**
|
||||
* @name isChildClass
|
||||
* @summary Tests if the child extends the parent Class
|
||||
* @description
|
||||
* Checks to see if the child Class extends the parent Class
|
||||
* @example
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import { isChildClass } from '@polkadot/util';
|
||||
*
|
||||
* console.log('isChildClass', isChildClass(BN, BN); // => true
|
||||
* console.log('isChildClass', isChildClass(BN, Uint8Array); // => false
|
||||
* ```
|
||||
*/
|
||||
export default function isChildClass <P extends Constructor> (Parent: P, Child?: Constructor | null | unknown): Child is P {
|
||||
// https://stackoverflow.com/questions/30993434/check-if-a-constructor-inherits-another-in-es6/30993664
|
||||
return Child
|
||||
// eslint-disable-next-line no-prototype-builtins
|
||||
? Parent === Child || Parent.isPrototypeOf(Child as Constructor)
|
||||
: false;
|
||||
}
|
||||
@@ -5,10 +5,11 @@
|
||||
/**
|
||||
* @summary Type checking utilities
|
||||
*/
|
||||
|
||||
export { default as isBigInt } from './bigInt';
|
||||
export { default as isBn } from './bn';
|
||||
export { default as isBuffer } from './buffer';
|
||||
export { default as isBoolean } from './boolean';
|
||||
export { default as isChildClass } from './childClass';
|
||||
export { default as isError } from './error';
|
||||
export { default as isFunction } from './function';
|
||||
export { default as isHex } from './hex';
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
import { Logger, Logger$Data } from './types';
|
||||
|
||||
import chalk from 'chalk';
|
||||
import moment from 'moment';
|
||||
|
||||
import formatDate from './format/formatDate';
|
||||
import isBn from './is/bn';
|
||||
import isBuffer from './is/buffer';
|
||||
import isFunction from './is/function';
|
||||
@@ -81,7 +81,7 @@ function apply (log: LogType, type: string, values: Logger$Data): void {
|
||||
chalked[log](value);
|
||||
|
||||
console[logTo[log] as 'log'](
|
||||
chalk(moment().format('YYYY-MM-DD HH:mm:ss')),
|
||||
chalk(formatDate(new Date())),
|
||||
chalk(type),
|
||||
...values.map(format)
|
||||
);
|
||||
|
||||
@@ -26,9 +26,5 @@ export default function numberToHex (value?: number | null, bitLength = -1): str
|
||||
return '0x';
|
||||
}
|
||||
|
||||
return hexFixLength(
|
||||
(value || 0).toString(16),
|
||||
bitLength,
|
||||
true
|
||||
);
|
||||
return hexFixLength(value.toString(16), bitLength, true);
|
||||
}
|
||||
|
||||
@@ -17,9 +17,7 @@
|
||||
* ```
|
||||
*/
|
||||
export default function stringLowerFirst (value?: string | null): string {
|
||||
if (!value) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return value.charAt(0).toLowerCase() + value.slice(1);
|
||||
return value
|
||||
? value.charAt(0).toLowerCase() + value.slice(1)
|
||||
: '';
|
||||
}
|
||||
|
||||
@@ -37,9 +37,7 @@ try {
|
||||
* ```
|
||||
*/
|
||||
export default function stringToU8a (value?: string): Uint8Array {
|
||||
if (!value) {
|
||||
return new Uint8Array([]);
|
||||
}
|
||||
|
||||
return encoder.encode(value);
|
||||
return value
|
||||
? encoder.encode(value)
|
||||
: new Uint8Array([]);
|
||||
}
|
||||
|
||||
@@ -17,9 +17,7 @@
|
||||
* ```
|
||||
*/
|
||||
export default function stringUpperFirst (value?: string | null): string {
|
||||
if (!value) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return value.charAt(0).toUpperCase() + value.slice(1);
|
||||
return value
|
||||
? value.charAt(0).toUpperCase() + value.slice(1)
|
||||
: '';
|
||||
}
|
||||
|
||||
@@ -4,6 +4,12 @@
|
||||
|
||||
import BN from 'bn.js';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export interface Constructor<T = any> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
new(...value: any[]): T;
|
||||
}
|
||||
|
||||
export interface ToBn {
|
||||
toBn: () => BN;
|
||||
}
|
||||
|
||||
@@ -23,9 +23,7 @@ export default function u8aFixLength (value: Uint8Array, bitLength = -1, atStart
|
||||
|
||||
if (bitLength === -1 || value.length === byteLength) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (value.length > byteLength) {
|
||||
} else if (value.length > byteLength) {
|
||||
return value.subarray(0, byteLength);
|
||||
}
|
||||
|
||||
|
||||
@@ -26,10 +26,7 @@ import { ToBnOptions } from '../types';
|
||||
* u8aToHex(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0xf])); // 0x68656c0f
|
||||
* ```
|
||||
*/
|
||||
export default function u8aToBn (
|
||||
value: Uint8Array,
|
||||
options: ToBnOptions | boolean = { isLe: true, isNegative: false }
|
||||
): BN {
|
||||
export default function u8aToBn (value: Uint8Array, options: ToBnOptions | boolean = { isLe: true, isNegative: false }): BN {
|
||||
return hexToBn(
|
||||
u8aToHex(value),
|
||||
options
|
||||
|
||||
@@ -17,9 +17,7 @@
|
||||
* ```
|
||||
*/
|
||||
export default function u8aToBuffer (value?: Uint8Array | null): Buffer {
|
||||
if (!value) {
|
||||
return Buffer.from([]);
|
||||
}
|
||||
|
||||
return Buffer.from(value);
|
||||
return !value
|
||||
? Buffer.from([])
|
||||
: Buffer.from(value);
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ export default function u8aToHex (value?: Uint8Array | null, bitLength = -1, isP
|
||||
? '0x'
|
||||
: '';
|
||||
|
||||
if (!value || !value.length) {
|
||||
if (!value?.length) {
|
||||
return prefix;
|
||||
}
|
||||
|
||||
|
||||
@@ -33,9 +33,7 @@ try {
|
||||
* ```
|
||||
*/
|
||||
export default function u8aToString (value?: Uint8Array | null): string {
|
||||
if (!value || !value.length) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return decoder.decode(value);
|
||||
return !value?.length
|
||||
? ''
|
||||
: decoder.decode(value);
|
||||
}
|
||||
|
||||
@@ -27,21 +27,15 @@ import stringToU8a from '../string/toU8a';
|
||||
export default function u8aToU8a (value?: number[] | Buffer | Uint8Array | string | null): Uint8Array {
|
||||
if (!value) {
|
||||
return new Uint8Array();
|
||||
}
|
||||
|
||||
if (isBuffer(value)) {
|
||||
} else if (isBuffer(value)) {
|
||||
return bufferToU8a(value);
|
||||
}
|
||||
|
||||
if (isString(value)) {
|
||||
} else if (isString(value)) {
|
||||
return isHex(value)
|
||||
? hexToU8a(value)
|
||||
: stringToU8a(value);
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return Uint8Array.from(value);
|
||||
}
|
||||
|
||||
return value;
|
||||
return Array.isArray(value)
|
||||
? Uint8Array.from(value)
|
||||
: value;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user