Compare commits

..
11 Commits
Author SHA1 Message Date
Github Actions cc8639565d [CI Skip] release/stable 2.12.2
skip-checks: true
2020-06-02 08:31:51 +00:00
Jaco Greeff b77d2e6860 Linting 2020-06-02 10:28:25 +02:00
Jaco Greeff e1fbd8ff9f 2.12.2 2020-06-02 10:22:30 +02:00
Github Actions f56dd32b4a [CI Skip] release/stable 2.12.1
skip-checks: true
2020-06-01 16:09:53 +00:00
Jaco Greeff 6077bef570 2.12 (#609) 2020-06-01 18:05:55 +02:00
Github Actions 377d83d4ed [CI Skip] release/beta 2.12.0-beta.2
skip-checks: true
2020-06-01 08:31:12 +00:00
Jaco Greeff bdb14f91a8 Pre-checks on verify input lengths (#608)
* Pre-checks on verify input lengths

* Small cleanup

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

* Cleanup

* Pre-allocate arrays

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

* Remove mnemonicToSeed
2020-05-31 14:19:10 +02:00
42 changed files with 1802 additions and 1049 deletions
+1 -1
View File
@@ -1,2 +1,2 @@
5
2.6.2
2.6.22.12.2
+2 -5
View File
@@ -10,7 +10,7 @@ jobs:
matrix:
step: ['build:release', 'docs:release']
name: ${{ matrix.step }}
if: "! contains(github.event.head_commit.message, '[CI Skip]') && github.repository == 'polkadot-js/common'"
if: "! startsWith(github.event.head_commit.message, '[CI Skip]') && github.repository == 'polkadot-js/common'"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
@@ -21,16 +21,13 @@ jobs:
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
GH_PAGES_SRC: build-docs
GH_PAT: ${{ secrets.GH_PAT }}
GH_TOKEN: ${{ secrets.GH_PAT }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_RELEASE_GITHUB_API_TOKEN: ${{ secrets.GH_PAT }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
yarn install --immutable | grep -v 'YN0013'
yarn ${{ matrix.step }}
dummy:
name: Dummy
if: "contains(github.event.head_commit.message, '[CI Skip]')"
runs-on: ubuntu-latest
steps:
- name: dummy
+83 -69
View File
@@ -1,34 +1,48 @@
# 2.11.1 May 26, 2020
# CHANGELOG
## 2.12.2 Jun 1, 2020
- Fix `isFunction` signature to assert `Function`
## 2.12.1 Jun 1, 2020
- **Important** Removed `mnemonicToSeed`, it is only for bip39, use `mnemonicToMiniSecret` for the Substrate variant
- Added `u8aEq` to compare two Uint8Array or hex values for an exact match
- Added `addressEq` to compare two addresses (ss58, Uint8array or hex) for an exact match
- Throw error on `{nacl,schnorrkel}Verify` on invalid input lengths
- Performance optimizations in `u8aToHex` & `u8aConcat`
## 2.11.1 May 26, 2020
- Internal cleanups on typings
- Support for latest TypeScript, eslint & typescript-eslint
# 2.10.1 May 14, 2020
## 2.10.1 May 14, 2020
- Add Kulupu ss58 prefix as an allowed value (Thanks to https://github.com/sorpaas)
- Make the `TextEncoder` polyfill handle non-compliant Buffer implementations (newer versions of Jest)
- `DeriveJunction` now also allows for BigInt values (aligning with number types elsewhere)
- Small code-flow optimizations
# 2.9.1 Apr 30, 2020
## 2.9.1 Apr 30, 2020
- Add support for ECDSA keypairs (Thanks to https://github.com/akru)
- Added `createKeyMulti` & `createKeySub` to create utility sub & multi keys
- Added `u8aSorted` to sort `Uint8Arrays`
- Added `sortAddresses` to sort addresses based on their internal representation
# 2.8.1 Apr 9, 2020
## 2.8.1 Apr 9, 2020
- Keypair will now throw an error when attempting to sign/derive using a locked pair (Thanks to https://github.com/h4x3rotab)
- Cleanup `isDevelopment` regex to cater for chains such as `Westend Development`
# 2.7.1 Mar 31, 2020
## 2.7.1 Mar 31, 2020
- Add `bnSqrt` to calculate the integer sqrt via Newton iteration
- Allow for optional wasm-crypto, specifically via `@polkadot/util-crypto/noWasm`
- Misc. CI infrastructure cleanups
# 2.6.1 Feb 29, 2020
## 2.6.1 Feb 29, 2020
- **Breaking change** Following on the 2.0 release, `@polkadot/wasm` was updated to 1.1+. sr25510 now only verifies 0.8+ signatures, closing the loop on dropping Substrate 1.x-era support
- Add `signatureVerify (message: Uint8Array | string, signature: Uint8Array | string, addressOrPublicKey: Uint8Array | string): VerifyResult` to verify any signature, regardless of type. Returns validity & detected crypto type.
@@ -36,14 +50,14 @@
- Add `addressCheckChecksum (decoded: Uint8Array)` as an helper to extract and verify the ss58 checksum
- Swap to yarn 2, allow use in yarn 2 projects
# 2.5.1 Feb 22, 2020
## 2.5.1 Feb 22, 2020
- **Breaking change** (TypeScript only) The `*.d.ts` files now contain TypeScript 3.8 features, `#private`, which is not usable in older versions
- Add `isBigInt(value)` to allow `BigInt` checks. Also add support in `bnToBn` as well as number conversion utils
- Add `isChildClass(Parent, Child?)` to check if a class extends the parent, asserting Child is Parent
- (internal) Use `#<field>` instead of `private _<field>` for private class variables
# 2.4.1 Feb 18, 2020
## 2.4.1 Feb 18, 2020
- Ensure that `formatBalance` does not apply unit overrides apply when no SI is applicable
- Adjust `formatBalance(<balance>, <options>)` to take expanded `withUnit: string | boolean` option where string is an actual unit, e.g. `KSM`
@@ -51,22 +65,22 @@
- The `.setSS58Format` on keyring will now just operate on pairs created on the keyring, not globally. The global `setSS58Format` in `@polkadot/util-crypto` will be deprecated.
- The deprecated `addressPrefix` option to keyring has been belatedly removed (Use `ss58Format` rather)
# 2.3.1 Feb 15, 2020
## 2.3.1 Feb 15, 2020
- Remove dependency on moment.js with `formatDate` function (Thanks to https://github.com/AndreasGassmann)
- Move TypeScript `@types/*` to dev deps (Thanks to https://github.com/AndreasGassmann)
- Update to `@polkadot/wasm-crypto` 1.0
- Cleanup dependencies to pave the way for using yarn 2 (Explicit instead of implicit)
# 2.2.1 Feb 06, 2020
## 2.2.1 Feb 06, 2020
- Add resolver for jest requires (tests from src)
# 2.1.1 Feb 04, 2020
## 2.1.1 Feb 04, 2020
- Update `detectPackage(<package.json>, __dirname?)` with calling folder
# 2.0.1 Jan 30, 2020
## 2.0.1 Jan 30, 2020
- Update w3f/schnorrkel to 0.8.5 (Full Substrate 2.x support, no 1.x support)
- Remove Alice session (ed2551) account from testing keyring (not applicable to Substrate 2.x)
@@ -74,27 +88,27 @@
- Renamed `assertSingletonPackage` to `detectPackage` with inclusion of version listing
- Swap to elliptic library for secp2561 recovery (No node bindings)
# 1.8.1 Jan 09, 2020
## 1.8.1 Jan 09, 2020
- Add cross-client encryption/decryption support (Thanks to https://github.com/hskang9)
# 1.7.1 Nov 27, 2019
## 1.7.1 Nov 27, 2019
- `formatBalance` signature now allows to force unit displays
- Keypair now allows for derive on a pair, with `pair.derive(...)`
- `assert` now acts like a real asserts, with no return - signature adapted for new TS 3.7
# 1.6.1 Oct 24, 2019
## 1.6.1 Oct 24, 2019
- `pair.sign(message)` now takes an optional second `options?: SignOptions` parameter, where `SignOptions` is currently defined as `{ withType: boolean }`. Here `withType` instructs the signing to prepend the type of signature (ed2551, sr25519 or ecdsa). This is used for the new Polkadot/Substrate MultiSignature format.
# 1.5.1 Sep 25, 2019
## 1.5.1 Sep 25, 2019
- Fix typings on the Keyring-exposed encode & decodeAddress
- Allow ss58Format = 0 as a valid value
- Loosen type definitions for allowed ss58format values (still checked against allowed array)
# 1.4.1 Sep 12, 2019
## 1.4.1 Sep 12, 2019
- **Breaking change** To set the `ss58Format`, you should now use `setSS58Format` as opposed to the old `setAddressPrefix`
- Renamed `keyring.setAddressPrefix` to `keyring.setSS58Format`
@@ -102,25 +116,25 @@
- Added `stringToHex` and `hexToString` conversion utilities to `@polkadot/util`
- Swap to [Babel 7.6.0](https://babeljs.io/) for all compilation, for latest improvements in code generation
# 1.3.1 Sep 10, 2019
## 1.3.1 Sep 10, 2019
- Remove the `ExtError` class, always prefer the standard JS `Error` object for errors. This would bre a breaking change for any applications using `ExtError`
# 1.2.1 Sep 09, 2019
## 1.2.1 Sep 09, 2019
- Keyring `addFromAddress` can now be used to store external accounts, for example those provided by external signers
- Maintainability updates
# 1.1.1 Aug 09, 2019
## 1.1.1 Aug 09, 2019
- `assertSingletonPackage` now warns via console.warn, but does not throw. This does allow the info to come accross while still allowing the app developers using multiple libraries time to fix.
# 1.0.1 Aug 02, 2019
## 1.0.1 Aug 02, 2019
- `formatBalance` now allows for `Compact` inputs
- `formaBalance` now allows correct formatting of very large decimals
# 0.94.1 Jul 20, 2019
### 0.94.1 Jul 20, 2019
- Add `checkAddress(address, prefix)` to `@polkadot/util-crypto` that validates an ss-58 address
- Add support for the Kusama network (as a valid checked prefix)
@@ -128,7 +142,7 @@
- The ed25519 key for Alice (representing the session), now appears in the test keyrings
- Fix missing dependencies for keyring (after address moves in 0.93.1)
# 0.93.1 Jun 14, 2019
### 0.93.1 Jun 14, 2019
- Breaking: External pair interface for keyring has been changed. Instead of
- `getMeta` use the `meta` getter, i.e. `console.log(pair.meta.name)`
@@ -136,133 +150,133 @@
- `publicKey` use the `publicKey` getter, i.e. `console.log(pair.publicKey)`
- `Move decodeAddress`, `encodeAddress` & `setAddressPrefix` functions into `@polkadot/util-crypto` from `@polkadot/keyring`. External interfaces should not be affected at this point since it is also (still) exported and exposed on keyring
# 0.92.1 Jun 04, 2019
### 0.92.1 Jun 04, 2019
- Only allow integer input values into `formatBalance`
- Allow `formatBalance`, `formatDecimal` & `formatNumber` to cater for negative numbers
- Add 'Bob//stash' to testing keyring, joining the existing 'Alice//stash'
# 0.91.1 May 22, 2019
### 0.91.1 May 22, 2019
- ed25519/sr25519 sign & verify functions can now take the message input as Uint8Array/string/hex and verify allows for the signature/publicKey to be specified as Uint8Array/hex
- Update `@polkadot/wasm` to include a maintenance bump for the `w3f/schnorrkel` libraries
# 0.90.1 May 08, 2019
### 0.90.1 May 08, 2019
- Moving towards 1.0
- Added bnMin & bnMax functions
# 0.76.1 Apr 03, 2019
### 0.76.1 Apr 03, 2019
- Fix `addFromMnemonic` to generate using new-style derivation.
- Pull in `formatBalance`, `formatDecimal`, `formatElapsed`, `formatNumber`, `calcSi`, `findSi` & `isTestChain` utility functions from the originals in `@polkadot/ui-util`
- Swap out `wasm-schnorrkel` & `wasm-ed25519` for combined version with `wasm-crypto`
- Swap DB interfaces to optional LRU, removing `transactionAsync` (client-only changes)
# 0.75.1 Mar 29, 2019
### 0.75.1 Mar 29, 2019
- Start journey to 1.0
# 0.42.1 Mar 28, 2019
### 0.42.1 Mar 28, 2019
- Add `assertSingletonPackage` to util
- Ensure that only a single keyring instance is loaded (uses above)
# 0.41.1 Mar 25, 2019
### 0.41.1 Mar 25, 2019
- Extensions to the client-specific database interfaces (non-breaking for API and util users)
# 0.40.1 Mar 23, 2019
### 0.40.1 Mar 23, 2019
- Add additional derivation path extraction mechanisms to util-crypto
- Add createFromUri function to keypair (creates keypair, does not add it)
- Allow all crypto hashing & ed25519 to use WASM (as available, JS fallbacks)
# 0.39.1 Mar 20, 2019
### 0.39.1 Mar 20, 2019
- Pull in bip39 generation functions from `@poladkot/wasm-crypto` with a fallback to the pure JS versions
# 0.38.1 Mar 18, 2019
### 0.38.1 Mar 18, 2019
- Align with current substrate master for sr25519 keys and hard/soft derivation
- Swap default dev keys to derived (sr25519)
# 0.37.1 Mar 14, 2019
### 0.37.1 Mar 14, 2019
- Swap to publishing -beta.x on merge (non-breaking testing)
# 0.36.1 Mar 13, 2019
### 0.36.1 Mar 13, 2019
- Add `fromUri` to keyring along with hard & soft key derivation.
# 0.35.1 Mar 04, 2019
### 0.35.1 Mar 04, 2019
- Remove NodeJs-only `syncify` function, not exported by the package (with binary dependency for Node)
# 0.34.1 Feb 13, 2019
### 0.34.1 Feb 13, 2019
- Keyring now allows for ed25519 and sr25519 instances. Upon creation, you need to pass the `ed25519`or `sr25519` string to denote the type, i.e. `new Keyring({ type: 'sr25519' })`
# 0.33.1 Nov 22, 2018
### 0.33.1 Nov 22, 2018
# 0.32.1 Oct 18, 2018
### 0.32.1 Oct 18, 2018
# 0.31.1 Oct 12, 2018
### 0.31.1 Oct 12, 2018
# 0.30.1 Sep 11, 2018
### 0.30.1 Sep 11, 2018
# 0.29.1 Sep 01, 2018
### 0.29.1 Sep 01, 2018
# 0.28.1 Aug 11, 2018
### 0.28.1 Aug 11, 2018
# 0.27.1 Aug 06, 2018
### 0.27.1 Aug 06, 2018
# 0.26.1 Jun 27, 2018
### 0.26.1 Jun 27, 2018
# 0.25.1 Jun 26, 2018
### 0.25.1 Jun 26, 2018
# 0.24.1 Jun 22, 2018
### 0.24.1 Jun 22, 2018
# 0.23.1 Jun 21, 2018
### 0.23.1 Jun 21, 2018
# 0.22.1 May 24, 2018
### 0.22.1 May 24, 2018
# 0.21.1 May 17, 2018
### 0.21.1 May 17, 2018
# 0.20.1 May 16, 2018
### 0.20.1 May 16, 2018
# 0.19.1 Apr 19, 2018
### 0.19.1 Apr 19, 2018
# 0.18.1 Mar 20, 2018
### 0.18.1 Mar 20, 2018
# 0.17.1 Mar0 8, 2018
### 0.17.1 Mar0 8, 2018
# 0.16.1 Feb 23, 2018
### 0.16.1 Feb 23, 2018
# 0.15.1 Feb 15, 2018
### 0.15.1 Feb 15, 2018
# 0.14.1 Feb 07, 2018
### 0.14.1 Feb 07, 2018
# 0.13.1 Jan 25, 2018
### 0.13.1 Jan 25, 2018
# 0.12.1 Jan 11, 2018
### 0.12.1 Jan 11, 2018
# 0.11.1 Dec 30, 2017
### 0.11.1 Dec 30, 2017
# 0.10.1 Dec 17, 2017
### 0.10.1 Dec 17, 2017
# 0.9.1 Dec 14, 2017
### 0.9.1 Dec 14, 2017
# 0.8.1 Dec 12, 2017
### 0.8.1 Dec 12, 2017
# 0.7.1 Dec 11, 2017
### 0.7.1 Dec 11, 2017
# 0.6.1 Nov 30, 2017
### 0.6.1 Nov 30, 2017
# 0.5.1 Nov 20, 2017
### 0.5.1 Nov 20, 2017
# 0.4.1 Nov 19, 2017
### 0.4.1 Nov 19, 2017
# 0.3.1 Nov 19, 2017
### 0.3.1 Nov 19, 2017
# 0.2.1 Nov 18, 2017
### 0.2.1 Nov 18, 2017
+1 -1
View File
@@ -9,5 +9,5 @@
"packages": [
"packages/*"
],
"version": "2.11.1"
"version": "2.12.2"
}
+4 -3
View File
@@ -22,8 +22,9 @@
},
"devDependencies": {
"@babel/core": "^7.9.6",
"@polkadot/dev": "^0.54.1",
"@polkadot/ts": "^0.3.23",
"@polkadot/dev": "^0.55.6",
"@polkadot/ts": "^0.3.25",
"@types/jest": "^25.2.3"
}
},
"version": "2.12.2"
}
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/keyring",
"version": "2.11.1",
"version": "2.12.2",
"description": "Keyring management",
"main": "index.js",
"publishConfig": {
@@ -28,7 +28,7 @@
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/keyring#readme",
"dependencies": {
"@babel/runtime": "^7.9.6",
"@polkadot/util": "2.11.1",
"@polkadot/util-crypto": "2.11.1"
"@polkadot/util": "2.12.2",
"@polkadot/util-crypto": "2.12.2"
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/util-crypto",
"version": "2.11.1",
"version": "2.12.2",
"description": "A collection of useful crypto utilities for @polkadot",
"main": "index.js",
"keywords": [
@@ -26,7 +26,7 @@
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util-crypto#readme",
"dependencies": {
"@babel/runtime": "^7.9.6",
"@polkadot/util": "2.11.1",
"@polkadot/util": "2.12.2",
"@polkadot/wasm-crypto": "^1.2.1",
"base-x": "^3.0.8",
"bip39": "^3.0.2",
+1 -2
View File
@@ -19,8 +19,7 @@ export default function decode (encoded: string | Uint8Array, ignoreChecksum?: b
}
const decoded = bufferToU8a(bs58.decode(encoded));
const error = (message: string): string =>
`Decoding ${encoded as string}: ${message}`;
const error = (message: string) => `Decoding ${encoded as string}: ${message}`;
// assert(defaults.allowedPrefix.includes(decoded[0] as Prefix), error('Invalid decoded address prefix'));
assert(defaults.allowedEncodedLengths.includes(decoded.length), error('Invalid decoded address length'));
@@ -2,7 +2,8 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import testingPairs from '../../../keyring/src/testingPairs';
import testingPairs from '@polkadot/keyring/testingPairs';
import encode from './encode';
const keyring = testingPairs({ type: 'ed25519' }, false);
@@ -20,7 +20,6 @@ export default function encode (_key: Uint8Array | string, ss58Format: Prefix =
assert(defaults.allowedDecodedLengths.includes(key.length), `Expected a valid key to convert, with length ${defaults.allowedDecodedLengths.join(', ')}`);
const isPublicKey = key.length === 32;
const input = u8aConcat(new Uint8Array([ss58Format]), key);
const hash = sshash(input);
@@ -0,0 +1,46 @@
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import testingPairs from '@polkadot/keyring/testingPairs';
import { addressEq } from '.';
describe('addressEq', (): void => {
it('returns false with non-equal', (): void => {
expect(
addressEq(
'5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
'5EnxxUmEbw8DkENKiYuZ1DwQuMoB2UWEQJZZXrTsxoz7SpgG'
)
).toEqual(false);
});
it('returns true for equal, matching prefix', (): void => {
expect(
addressEq(
'5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
'5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'
)
).toEqual(true);
});
it('returns true for equal, non-matching prefix', (): void => {
expect(
addressEq(
'5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
'7sL6eNJj5ZGV5cn3hhV2deRUsivXfBfMH76wCALCqWj1EKzv'
)
).toEqual(true);
});
it('returns true for equal, address vs publicKey', (): void => {
const keyring = testingPairs({ type: 'sr25519' });
expect(
addressEq(
'5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
keyring.alice.publicKey
)
).toEqual(true);
});
});
+25
View File
@@ -0,0 +1,25 @@
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { u8aEq } from '@polkadot/util';
import decode from './decode';
/**
* @name addressEq
* @summary Compares two addresses, either in ss58, Uint8Array or hex format.
* @description
* For the input values, return true is the underlying public keys do match.
* @example
* <BR>
*
* ```javascript
* import { u8aEq } from '@polkadot/util';
*
* u8aEq(new Uint8Array([0x68, 0x65]), new Uint8Array([0x68, 0x65])); // true
* ```
*/
export default function addressEq (a: string | Uint8Array, b: string | Uint8Array): boolean {
return u8aEq(decode(a), decode(b));
}
@@ -8,10 +8,12 @@ import createKeyMulti from './keyMulti';
import createKeySub from './keySub';
import decodeAddress from './decode';
import encodeAddress from './encode';
import addressEq from './eq';
import setSS58Format from './setSS58Format';
import sortAddresses from './sort';
export {
addressEq,
checkAddress,
checkAddressChecksum,
createKeyMulti,
+4 -2
View File
@@ -3,15 +3,17 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import BN from 'bn.js';
import { bnToU8a, compactToU8a, u8aConcat, u8aSorted } from '@polkadot/util';
import { bnToU8a, compactToU8a, stringToU8a, u8aConcat, u8aSorted } from '@polkadot/util';
import blake2AsU8a from '../blake2/asU8a';
import decodeAddress from './decode';
const PREFIX = stringToU8a('modlpy/utilisuba');
export default function createKeyMulti (who: (Uint8Array | string)[], threshold: BigInt | BN | number): Uint8Array {
return blake2AsU8a(
u8aConcat(
'modlpy/utilisuba',
PREFIX,
compactToU8a(who.length),
...u8aSorted(who.map((who) => decodeAddress(who))),
bnToU8a(threshold, { bitLength: 16, isLe: true })
+4 -2
View File
@@ -3,15 +3,17 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import BN from 'bn.js';
import { bnToU8a, u8aConcat } from '@polkadot/util';
import { bnToU8a, stringToU8a, u8aConcat } from '@polkadot/util';
import blake2AsU8a from '../blake2/asU8a';
import decodeAddress from './decode';
const PREFIX = stringToU8a('modlpy/utilisuba');
export default function createKeySub (who: Uint8Array | string, index: BigInt | BN | number): Uint8Array {
return blake2AsU8a(
u8aConcat(
'modlpy/utilisuba',
PREFIX,
decodeAddress(who),
bnToU8a(index, { bitLength: 16, isLe: true })
)
+1 -1
View File
@@ -13,7 +13,7 @@ export interface ExtractResult {
}
/**
* @description Extract derivation juntions from the supplied path
* @description Extract derivation junctions from the supplied path
*/
export default function keyExtractPath (derivePath: string): ExtractResult {
const parts = derivePath.match(RE_JUNCTION);
+7 -5
View File
@@ -9,12 +9,14 @@ import keyHdkdEd15519 from './hdkdEd25519';
import keyHdkdSr15519 from './hdkdSr25519';
import keyHdkdEcdsa from './hdkdEcdsa';
const generators = {
ecdsa: keyHdkdEcdsa,
ed25519: keyHdkdEd15519,
sr25519: keyHdkdSr15519
};
export default function keyFromPath (pair: Keypair, path: DeriveJunction[], type: KeypairType): Keypair {
const keyHdkd = {
ecdsa: keyHdkdEcdsa,
ed25519: keyHdkdEd15519,
sr25519: keyHdkdSr15519
}[type];
const keyHdkd = generators[type];
return path.reduce((pair, junction): Keypair => {
return keyHdkd(pair, junction);
@@ -11,5 +11,4 @@ import '../polyfill';
export { default as mnemonicGenerate } from './generate';
export { default as mnemonicToEntropy } from './toEntropy';
export { default as mnemonicToMiniSecret } from './toMiniSecret';
export { default as mnemonicToSeed } from './toSeed';
export { default as mnemonicValidate } from './validate';
@@ -1,15 +0,0 @@
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { u8aToHex } from '@polkadot/util';
import toSeed from './toSeed';
describe('mnemonicToSeed', (): void => {
it('generates a valid seed', (): void => {
expect(
u8aToHex(toSeed('seed sock milk update focus rotate barely fade car face mechanic mercy'))
).toEqual('0x3c121e20de068083b49c2315697fb59a2d9e8643c24e5ea7628132c58969a027');
});
});
@@ -1,30 +0,0 @@
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { mnemonicToSeedSync } from 'bip39';
import { bufferToU8a } from '@polkadot/util';
import { bip39ToSeed, isReady } from '@polkadot/wasm-crypto';
/**
* @name toSeed
* @summary Creates a valid seed from a mnemonic input
* @example
* <BR>
*
* ```javascript
* import { mnemonicGenerate, mnemonicToSeed, mnemonicValidate } from '@polkadot/util-crypto';
*
* const mnemonic = mnemonicGenerate(); // => string
* const isValidMnemonic = mnemonicValidate(mnemonic); // => boolean
*
* if (isValidMnemonic) {
* console.log(`Seed generated from mnemonic: ${mnemonicToSeed(mnemonic)}`); => u8a
* }
* ```
*/
export default function toSeed (mnemonic: string, password = ''): Uint8Array {
return isReady()
? bip39ToSeed(mnemonic, password)
: bufferToU8a(mnemonicToSeedSync(mnemonic, password)).subarray(0, 32);
}
+1 -1
View File
@@ -23,7 +23,7 @@ import { isReady, ed25519Sign } from '@polkadot/wasm-crypto';
* ```
*/
export default function naclSign (message: Uint8Array | string, { publicKey, secretKey }: Partial<Keypair>): Uint8Array {
assert(secretKey, 'Expected valid secretKey');
assert(secretKey, 'Expected a valid secretKey');
const messageU8a = u8aToU8a(message);
+21 -1
View File
@@ -7,7 +7,7 @@ import { waitReady } from '@polkadot/wasm-crypto';
import { naclVerify, naclKeypairFromSeed } from '.';
describe('naclSign', (): void => {
describe('naclVerify', (): void => {
let publicKey: Uint8Array;
let signature: Uint8Array;
@@ -51,4 +51,24 @@ describe('naclSign', (): void => {
)
).toEqual(false);
});
it('throws error when publicKey lengths do not match', (): void => {
expect(
() => naclVerify(
new Uint8Array([0x61, 0x62, 0x63, 0x64]),
signature,
new Uint8Array([1, 2])
)
).toThrow(/Invalid publicKey/);
});
it('throws error when signature lengths do not match', (): void => {
expect(
() => naclVerify(
new Uint8Array([0x61, 0x62, 0x63, 0x64]),
new Uint8Array([1, 2]),
publicKey
)
).toThrow(/Invalid signature/);
});
});
+6 -3
View File
@@ -3,14 +3,14 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import nacl from 'tweetnacl';
import { u8aToU8a } from '@polkadot/util';
import { assert, u8aToU8a } from '@polkadot/util';
import { isReady, ed25519Verify } from '@polkadot/wasm-crypto';
/**
* @name naclSign
* @summary Verifies the signature on the supplied message.
* @description
* Verifies the `signature` on `message` with the supplied `plublicKey`. Returns `true` on sucess, `false` otherwise.
* Verifies the `signature` on `message` with the supplied `publicKey`. Returns `true` on sucess, `false` otherwise.
* @example
* <BR>
*
@@ -22,8 +22,11 @@ import { isReady, ed25519Verify } from '@polkadot/wasm-crypto';
*/
export default function naclVerify (message: Uint8Array | string, signature: Uint8Array | string, publicKey: Uint8Array | string): boolean {
const messageU8a = u8aToU8a(message);
const signatureU8a = u8aToU8a(signature);
const publicKeyU8a = u8aToU8a(publicKey);
const signatureU8a = u8aToU8a(signature);
assert(publicKeyU8a.length === 32, `Invalid publicKey, received ${publicKeyU8a.length}, expected 32`);
assert(signatureU8a.length === 64, `Invalid signature, received ${signatureU8a.length} bytes, expected 64`);
return isReady()
? ed25519Verify(signatureU8a, messageU8a, publicKeyU8a)
+2 -2
View File
@@ -14,8 +14,8 @@ import { sr25519Sign } from '@polkadot/wasm-crypto';
* @description Returns message signature of `message`, using the supplied pair
*/
export default function schnorrkelSign (message: Uint8Array | string, { publicKey, secretKey }: Partial<Keypair>): Uint8Array {
assert(publicKey?.length === 32, 'Expected valid publicKey, 32-bytes');
assert(secretKey?.length === 64, 'Expected valid secretKey, 64-bytes');
assert(publicKey?.length === 32, 'Expected a valid publicKey, 32-bytes');
assert(secretKey?.length === 64, 'Expected a valid secretKey, 64-bytes');
const messageU8a = u8aToU8a(message);
@@ -29,4 +29,24 @@ describe('sign and verify', (): void => {
expect(verify(MESSAGE, signature, pair.publicKey)).toBe(true);
});
it('throws error when publicKey lengths do not match', (): void => {
expect(
() => verify(
new Uint8Array([0x61, 0x62, 0x63, 0x64]),
new Uint8Array(64),
new Uint8Array(31)
)
).toThrow(/Invalid publicKey/);
});
it('throws error when signature lengths do not match', (): void => {
expect(
() => verify(
new Uint8Array([0x61, 0x62, 0x63, 0x64]),
new Uint8Array(65),
new Uint8Array(32)
)
).toThrow(/Invalid signature/);
});
});
@@ -4,7 +4,7 @@
import '../polyfill';
import { u8aToU8a } from '@polkadot/util';
import { assert, u8aToU8a } from '@polkadot/util';
import { sr25519Verify } from '@polkadot/wasm-crypto';
/**
@@ -13,8 +13,11 @@ import { sr25519Verify } from '@polkadot/wasm-crypto';
*/
export default function schnorrkelVerify (message: Uint8Array | string, signature: Uint8Array | string, publicKey: Uint8Array | string): boolean {
const messageU8a = u8aToU8a(message);
const signatureU8a = u8aToU8a(signature);
const publicKeyU8a = u8aToU8a(publicKey);
const signatureU8a = u8aToU8a(signature);
assert(publicKeyU8a.length === 32, `Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
assert(signatureU8a.length === 64, `Invalid signature, received ${signatureU8a.length} bytes, expected 64`);
return sr25519Verify(signatureU8a, messageU8a, publicKeyU8a);
}
+2 -3
View File
@@ -67,10 +67,9 @@ export default function signatureVerify (message: Uint8Array | string, signature
const result: VerifyResult = { crypto: 'none', isValid: false };
const publicKey = addressDecode(addressOrPublicKey);
const isMultisig = [0, 1, 2].includes(signatureU8a[0]) && [65, 66].includes(signatureU8a.length);
const multisig = [0, 1, 2].includes(signatureU8a[0]) && [65, 66].includes(signatureU8a.length);
if (multisig) {
if (isMultisig) {
return verifyMultisig(result, message, signatureU8a, publicKey);
} else {
return verifyDetect(result, message, signatureU8a, publicKey);
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/util",
"version": "2.11.1",
"version": "2.12.2",
"description": "A collection of useful utilities for @polkadot",
"main": "index.js",
"keywords": [
+1 -1
View File
@@ -22,5 +22,5 @@ import assert from '../assert';
export default function max (...items: BN[]): BN {
assert(items && items.length >= 1, 'Must provide one or more BN arguments');
return items.reduce((acc: BN, val: BN): BN => BN.max(acc, val), items[0]);
return items.reduce((acc: BN, val: BN) => BN.max(acc, val), items[0]);
}
+1 -1
View File
@@ -22,5 +22,5 @@ import assert from '../assert';
export default function min (...items: BN[]): BN {
assert(items && items.length >= 1, 'Must provide one or more BN arguments');
return items.reduce((acc: BN, val: BN): BN => BN.min(acc, val), items[0]);
return items.reduce((acc: BN, val: BN) => BN.min(acc, val), items[0]);
}
+1 -1
View File
@@ -39,7 +39,7 @@ function flattenVersions (_all: (VersionPath | string)[]): string {
const verLength = all.reduce((max, { version }): number => Math.max(max, version.length), 0);
return all
.map(({ path, version }): string => `\t${version.padEnd(verLength)}\t${expandPath(path)}`)
.map(({ path, version }) => `\t${version.padEnd(verLength)}\t${expandPath(path)}`)
.join('\n');
}
+4 -2
View File
@@ -2,6 +2,9 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
// eslint-disable-next-line @typescript-eslint/ban-types
type FnType = Function;
/**
* @name isFunction
* @summary Tests for a `function`.
@@ -16,7 +19,6 @@
* isFunction(() => false); // => true
* ```
*/
// eslint-disable-next-line @typescript-eslint/ban-types
export default function isFunction (value: unknown): value is Function {
export default function isFunction (value: unknown): value is FnType {
return typeof value === 'function';
}
+2 -4
View File
@@ -67,8 +67,7 @@ export function format (value: unknown): unknown {
function apply (log: LogType, type: string, values: Logger$Data): void {
if (values.length === 1 && isFunction(values[0])) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/ban-types
const fnResult = (values[0] as Function)();
const fnResult = values[0]() as unknown;
return apply(log, type, Array.isArray(fnResult) ? fnResult : [fnResult]);
}
@@ -83,8 +82,7 @@ function apply (log: LogType, type: string, values: Logger$Data): void {
);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function noop (...values: Logger$Data): void {
function noop (): void {
// noop
}
+1 -2
View File
@@ -7,8 +7,7 @@ if (typeof TextDecoder === 'undefined') {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-var-requires
const { TextDecoder: UTD } = require('util') as { TextDecoder: { new(): TextDecoder } };
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-member-access
(global as any).TextDecoder = UTD;
global.TextDecoder = UTD;
} catch (error) {
// noop
}
+2 -2
View File
@@ -17,8 +17,8 @@
* await promisify(null, (cb) => cb(new Error('error!'))); // rejects with `error!`
* ```
*/
// eslint-disable-next-line @typescript-eslint/ban-types,@typescript-eslint/explicit-module-boundary-types,@typescript-eslint/no-explicit-any
export default function promisify <R = any> (self: unknown, fn: Function, ...params: any[]): Promise<R> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function promisify <R = any> (self: unknown, fn: (...params: any) => any, ...params: any[]): Promise<R> {
return new Promise((resolve, reject): void => {
const handler = (error: Error | null, result?: R): void => {
if (error) {
+2 -4
View File
@@ -20,10 +20,8 @@ export interface SiDef {
value: string;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Logger$Data$Fn = () => any[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type Logger$Data = (any | Logger$Data$Fn)[];
type Logger$Data$Fn = () => unknown[];
export type Logger$Data = (unknown | Logger$Data$Fn)[];
export interface Logger {
debug: (...values: Logger$Data) => void;
+16 -8
View File
@@ -21,15 +21,23 @@ import u8aToU8a from './toU8a';
* ); // [1, 2, 3, 4, 5, 6]
* ```
*/
export default function u8aConcat (..._list: (Uint8Array | string)[]): Uint8Array {
const list = _list.map(u8aToU8a);
const result = new Uint8Array(list.reduce((total, item): number => total + item.length, 0));
export default function u8aConcat (...list: (Uint8Array | string)[]): Uint8Array {
let length = 0;
let offset = 0;
const u8as = new Array(list.length) as Uint8Array[];
return list.reduce((result, item): Uint8Array => {
result.set(item, offset);
offset += item.length;
for (let i = 0; i < list.length; i++) {
u8as[i] = u8aToU8a(list[i]);
return result;
}, result);
length += u8as[i].length;
}
const result = new Uint8Array(length);
for (let i = 0; i < u8as.length; i++) {
result.set(u8as[i], offset);
offset += u8as[i].length;
}
return result;
}
+43
View File
@@ -0,0 +1,43 @@
// Copyright 2017-2020 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { u8aEq } from '.';
describe('u8aEq', (): void => {
it('returns false when the lengths do not match', (): void => {
expect(
u8aEq(
new Uint8Array([1, 2, 3]),
new Uint8Array([1, 2])
)
).toEqual(false);
});
it('returns false when the contents do not match', (): void => {
expect(
u8aEq(
new Uint8Array([1, 2, 3]),
new Uint8Array([1, 2, 4])
)
).toEqual(false);
});
it('returns true when the contents do match', (): void => {
expect(
u8aEq(
new Uint8Array([1, 2, 3]),
new Uint8Array([1, 2, 3])
)
).toEqual(true);
});
it('returns true with equalvalent hex & Uint8array', (): void => {
expect(
u8aEq(
'0x010203',
new Uint8Array([1, 2, 3])
)
).toEqual(true);
});
});
+37
View File
@@ -0,0 +1,37 @@
// Copyright 2017-2020 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import u8aToU8a from './toU8a';
function equals (a: Uint8Array, b: Uint8Array): boolean {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
/**
* @name u8aEq
* @summary Compares two Uint8Arrays.
* @description
* For `UInt8Array` (or hex string) input values true if there is a match.
* @example
* <BR>
*
* ```javascript
* import { u8aEq } from '@polkadot/util';
*
* u8aEq(new Uint8Array([0x68, 0x65]), new Uint8Array([0x68, 0x65])); // true
* ```
*/
export default function u8aEq (a: Uint8Array | string, b: Uint8Array | string): boolean {
return equals(u8aToU8a(a), u8aToU8a(b));
}
+1
View File
@@ -7,6 +7,7 @@
*/
export { default as u8aConcat } from './concat';
export { default as u8aEq } from './eq';
export { default as u8aFixLength } from './fixLength';
export { default as u8aSorted } from './sorted';
export { default as u8aToBn } from './toBn';
+12 -7
View File
@@ -2,7 +2,11 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
const ALPHABET = '0123456789abcdef';
const ALPHABET = new Array(256) as string[];
for (let n = 0; n < 256; ++n) {
ALPHABET[n] = n.toString(16).padStart(2, '0');
}
/**
* @name u8aToHex
@@ -35,10 +39,11 @@ export default function u8aToHex (value?: Uint8Array | null, bitLength = -1, isP
return `${u8aToHex(value.subarray(0, halfLength), -1, isPrefixed)}${u8aToHex(value.subarray(value.length - halfLength), -1, false)}`;
}
// based on comments in https://stackoverflow.com/questions/40031688/javascript-arraybuffer-to-hex and
// implementation in http://jsben.ch/Vjx2V - optimisation here suggests that a forEach loop is faster
// than reduce as well (clocking at in 90% of the reduce speed with tweaking in the playpen above)
return value.reduce((result, value): string => {
return result + ALPHABET[value >> 4] + ALPHABET[value & 15];
}, prefix);
const result = new Array(value.length) as string[];
for (let i = 0; i < value.length; i++) {
result[i] = ALPHABET[value[i]];
}
return prefix + result.join('');
}
+1433 -860
View File
File diff suppressed because it is too large Load Diff