Compare commits

..
38 Commits
Author SHA1 Message Date
Github Actions 9a5d2e00be [CI Skip] release/stable 7.5.1
skip-checks: true
2021-10-16 06:32:07 +00:00
Jaco 5f36b23dfc 7.5.1 (#1131)
* 7.5.1

* CHANGELOG
2021-10-16 09:24:45 +03:00
Github Actions 921659981d [CI Skip] release/beta 7.4.2-8
skip-checks: true
2021-10-14 06:43:02 +00:00
Jaco 1bcafead57 Parse derivation paths via BN (#1130)
* Parse derivation paths via BN

* Direct to u8a for numbers

* CHANGELOG
2021-10-14 09:34:13 +03:00
Github Actions 9b29d33d87 [CI Skip] release/beta 7.4.2-7
skip-checks: true
2021-10-14 05:59:53 +00:00
Jaco ecce4a22f7 networks:sync (#1129) 2021-10-14 08:51:13 +03:00
Github Actions 22d471d5fc [CI Skip] release/beta 7.4.2-6
skip-checks: true
2021-10-08 06:04:20 +00:00
Jaco 4df1a67be4 Bump deps (#1126) 2021-10-08 08:55:29 +03:00
Github Actions 497b97ad4e [CI Skip] release/beta 7.4.2-5
skip-checks: true
2021-10-02 05:58:25 +00:00
Jaco 9177b24d5b Sync ss58 (#1122) 2021-10-02 08:49:40 +03:00
Github Actions 88556d6a75 [CI Skip] release/beta 7.4.2-4
skip-checks: true
2021-09-29 12:59:41 +00:00
Jaco c8dfeaad5b Update ss58 JSON format handling (#1120)
* Update JSON handling

* Fix output
2021-09-29 14:51:19 +02:00
Github Actions 69190b0395 [CI Skip] release/beta 7.4.2-3
skip-checks: true
2021-09-29 08:29:52 +00:00
Tomokazu Kozumaandadmin e61cd53e08 fix comment (#1119)
Co-authored-by: admin <admin@adminnoMacBook-Air.local>
2021-09-29 10:20:59 +02:00
Github Actions 26b0630cd3 [CI Skip] release/beta 7.4.2-2
skip-checks: true
2021-09-28 12:08:54 +00:00
Jaco e09c604c26 ss58 sync (#1117) 2021-09-28 14:00:12 +02:00
Github Actions 7983a12121 [CI Skip] release/beta 7.4.2-1
skip-checks: true
2021-09-27 05:46:53 +00:00
Jaco 0e070c6142 Bump deps (#1115) 2021-09-27 07:39:56 +02:00
Github Actions e30a10a4b5 [CI Skip] release/beta 7.4.2-0
skip-checks: true
2021-09-24 17:46:51 +00:00
Antoine EstienneandJaco c3a073a952 Improve ethereum tests (#1114)
* added gerald test address

* improve ethereum tests

* lint

* Update packages/keyring/src/suri.spec.ts

Co-authored-by: Jaco <jacogr@gmail.com>

* remove seed for ethereum testing pairs

* lint

Co-authored-by: Jaco <jacogr@gmail.com>
2021-09-24 20:40:31 +03:00
Github Actions 203891d184 [CI Skip] release/stable 7.4.1
skip-checks: true
2021-09-17 14:12:48 +00:00
Jaco 4ea8ccf844 7.4.1 (#1112)
* 7.4.1

* CHANGELOG
2021-09-17 16:04:41 +02:00
Github Actions d7b856f8f0 [CI Skip] release/beta 7.3.2-7
skip-checks: true
2021-09-17 13:40:09 +00:00
Jaco b37d55e0ed Some attempted CC fixes (#1111)
* Some attempted CC fixes

* hmac

* adjust derive
2021-09-17 15:32:52 +02:00
Github Actions f1740dfdd7 [CI Skip] release/beta 7.3.2-6
skip-checks: true
2021-09-17 12:57:44 +00:00
Jaco 7047bf5aa5 Detect and verify wrapped messages (#1110)
* Detect and verify wrapped messages

* Expose isWrapped detection

* Complexity cleanups

* Update wrap.spec.ts

* Update wrap.ts

* Extract fn getter

* Test for wrapping to detect path
2021-09-17 14:48:33 +02:00
Github Actions 5dcf99eaa7 [CI Skip] release/beta 7.3.2-5
skip-checks: true
2021-09-14 18:18:25 +00:00
Jaco efc6b315e5 Networks:sync (#1109) 2021-09-14 20:09:47 +02:00
Github Actions 2ce554587f [CI Skip] release/beta 7.3.2-4
skip-checks: true
2021-09-14 11:32:59 +00:00
Jaco f1e45ee2c3 Bump deps (#1107) 2021-09-14 13:24:13 +02:00
Github Actions e5e46cedaf [CI Skip] release/beta 7.3.2-3
skip-checks: true
2021-09-13 11:20:26 +00:00
Jaco 2b7e21355d Sync ss58 registry (#1106) 2021-09-13 13:12:46 +02:00
Github Actions 2565712a79 [CI Skip] release/beta 7.3.2-2
skip-checks: true
2021-09-08 12:46:23 +00:00
Jaco 9fc57a23e8 Adjust isHex with template return (#1103)
* Adjust isHex with template return

* Unneeded assignment

* CHANGELOG

* typo

* Additional HexString types

* Additional HexString inputs

* Use U8aLike as applicable

* typo

* Unneeded type

* HexString outputs

* Export types
2021-09-08 14:38:53 +02:00
Github Actions 6b9b7fa7f5 [CI Skip] release/beta 7.3.2-1
skip-checks: true
2021-09-05 09:03:17 +00:00
Jaco c9f127ec72 Bump deps (#1101)
* Bump deps

* linting
2021-09-05 10:55:11 +02:00
Github Actions 89699f3f4e [CI Skip] release/beta 7.3.2-0
skip-checks: true
2021-09-01 16:47:31 +00:00
Jaco 7d167bcd4c Jest config cleanup (#1100) 2021-09-01 18:39:13 +02:00
117 changed files with 1851 additions and 2234 deletions
+26 -1
View File
@@ -1,5 +1,30 @@
# CHANGELOG
## 7.5.1 Oct 16, 2021
Contributed:
- Fix comment on `blake2AsU8a` (Thanks to https://github.com/tomokazukozuma)
- Update Ethereum derivation process (Thanks to https://github.com/joelamouche)
Changes:
- Derivation paths now caters for > `MAX_SAFE_INTEGER` unsigned values
- Sync with upstream Substrate ss58 registry
- Update ss58 registry handling (both previous and current versions)
## 7.4.1 Sep 17, 2021
Changes:
- Add `u8aWrapBytes` & `u8aUnwrapBytes` (originally from `@polkadot/extension-dapp`)
- Verify both wrapped and unwrapped signatures transparently
- Adjust `isHex` return to `0x${string}` under TypeScript
- Adjust shared repo Jest config
- Sync with upstream Substrate ss58 registry
## 7.3.1 Aug 28, 2021
Contributed:
@@ -10,7 +35,7 @@ Contributed:
Changes:
- Add support for `schnorrkelAgreement` (as exposed by new `wasm-crypto)
- Add support for `schnorrkelAgreement` (as exposed by new `wasm-crypto`)
- Ensure `schnorrkel*` functions allows hex inputs
- `@polkadot/wasm-crypto` 4.2.1
- Sync with upstream Substrate ss58 registry
+1 -17
View File
@@ -16,21 +16,5 @@ module.exports = Object.assign({}, config, {
'@polkadot/x-(fetch|randomvalues|textdecoder|textencoder|ws)(.*)$': '<rootDir>/packages/x-$1/src/node',
'@polkadot/x-global(.*)$': '<rootDir>/packages/x-global/src/$1',
'@polkadot/x-rxjs(.*)$': '<rootDir>/packages/x-rxjs/src/$1'
},
modulePathIgnorePatterns: [
'<rootDir>/packages/hw-ledger/build',
'<rootDir>/packages/hw-ledger-transports/build',
'<rootDir>/packages/keyring/build',
'<rootDir>/packages/networks/build',
'<rootDir>/packages/util/build',
'<rootDir>/packages/util-crypto/build',
'<rootDir>/packages/x-fetch/build',
'<rootDir>/packages/x-global/build',
'<rootDir>/packages/x-randomvalues/build',
'<rootDir>/packages/x-rxjs/build',
'<rootDir>/packages/x-textdecoder/build',
'<rootDir>/packages/x-textencoder/build',
'<rootDir>/packages/x-ws/build'
],
transformIgnorePatterns: ['/node_modules/(?!@polkadot)']
}
});
+6 -6
View File
@@ -7,7 +7,7 @@
"packages/*"
],
"resolutions": {
"typescript": "^4.3.5"
"typescript": "^4.4.4"
},
"scripts": {
"build": "polkadot-dev-build-ts",
@@ -23,12 +23,12 @@
"test:one": "polkadot-dev-run-test --runInBand"
},
"devDependencies": {
"@babel/core": "^7.15.0",
"@polkadot/dev": "^0.62.62",
"@polkadot/ts": "^0.4.6",
"@babel/core": "^7.15.8",
"@polkadot/dev": "^0.62.71",
"@polkadot/ts": "^0.4.9",
"@types/ed2curve": "^0.2.2",
"@types/jest": "^27.0.1"
"@types/jest": "^27.0.2"
},
"version": "7.3.1",
"version": "7.5.1",
"packageManager": "yarn@3.0.1"
}
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/hw-ledger-transports",
"version": "7.3.1",
"version": "7.5.1",
"type": "module",
"repository": "github:polkadot-js/common",
"author": "Jaco Greeff <jacogr@gmail.com>",
@@ -15,12 +15,12 @@
"node": ">=14.0.0"
},
"dependencies": {
"@babel/runtime": "^7.15.3",
"@ledgerhq/hw-transport": "^6.3.0",
"@ledgerhq/hw-transport-webhid": "^6.4.1",
"@ledgerhq/hw-transport-webusb": "^6.3.0"
"@babel/runtime": "^7.15.4",
"@ledgerhq/hw-transport": "^6.7.0",
"@ledgerhq/hw-transport-webhid": "^6.7.0",
"@ledgerhq/hw-transport-webusb": "^6.7.0"
},
"optionalDependencies": {
"@ledgerhq/hw-transport-node-hid-singleton": "^6.3.0"
"@ledgerhq/hw-transport-node-hid-singleton": "^6.7.0"
}
}
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/hw-ledger-transports', version: '7.3.1' };
export const packageInfo = { name: '@polkadot/hw-ledger-transports', version: '7.5.1' };
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/hw-ledger",
"version": "7.3.1",
"version": "7.5.1",
"type": "module",
"repository": "github:polkadot-js/common",
"author": "Jaco Greeff <jacogr@gmail.com>",
@@ -16,9 +16,9 @@
"node": ">=14.0.0"
},
"dependencies": {
"@babel/runtime": "^7.15.3",
"@polkadot/hw-ledger-transports": "7.3.1",
"@polkadot/util": "7.3.1",
"@babel/runtime": "^7.15.4",
"@polkadot/hw-ledger-transports": "7.5.1",
"@polkadot/util": "7.5.1",
"@zondax/ledger-substrate": "^0.18.0"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/hw-ledger', version: '7.3.1' };
export const packageInfo = { name: '@polkadot/hw-ledger', version: '7.5.1' };
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/keyring",
"version": "7.3.1",
"version": "7.5.1",
"type": "module",
"description": "Keyring management",
"author": "Jaco Greeff <jacogr@gmail.com>",
@@ -19,12 +19,12 @@
"bugs": "https://github.com/polkadot-js/common/issues",
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/keyring#readme",
"dependencies": {
"@babel/runtime": "^7.15.3",
"@polkadot/util": "7.3.1",
"@polkadot/util-crypto": "7.3.1"
"@babel/runtime": "^7.15.4",
"@polkadot/util": "7.5.1",
"@polkadot/util-crypto": "7.5.1"
},
"peerDependencies": {
"@polkadot/util": "7.3.1",
"@polkadot/util-crypto": "7.3.1"
"@polkadot/util": "7.5.1",
"@polkadot/util-crypto": "7.5.1"
}
}
+12
View File
@@ -121,6 +121,18 @@ describe('keypair', (): void => {
).toEqual('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY');
});
it('creates with integer derivations', (): void => {
// MAX_SAFE_INTEGER
expect(
keyring.createFromUri('//9007199254740991').address
).toEqual('5CDsyNZyqxLpHnTvknr68anUcYoBFjZbFKiEJJf4prB75Uog');
// MAX_SAFE_INTEGER + extra digits
expect(
keyring.createFromUri('//900719925474099999').address
).toEqual('5GHj2D7RG2m2DXYwGSDpXwuuxn53G987i7p2EQVDqP4NYu4q');
});
it('creates via dev seed (2-byte encoding)', (): void => {
keyring.setSS58Format(252);
+4 -6
View File
@@ -1,8 +1,7 @@
// Copyright 2017-2021 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { EncryptedJsonEncoding } from '@polkadot/util-crypto/json/types';
import type { Keypair, KeypairType } from '@polkadot/util-crypto/types';
import type { EncryptedJsonEncoding, Keypair, KeypairType } from '@polkadot/util-crypto/types';
import type { KeyringInstance, KeyringOptions, KeyringPair, KeyringPair$Json, KeyringPair$Meta } from './types';
import { assert, hexToU8a, isHex, isUndefined, stringToU8a } from '@polkadot/util';
@@ -206,17 +205,16 @@ export class Keyring implements KeyringInstance {
if (isPhraseHex) {
seed = hexToU8a(phrase);
} else {
const str = phrase;
const parts = str.split(' ');
const parts = phrase.split(' ');
if ([12, 15, 18, 21, 24].includes(parts.length)) {
seed = type === 'ethereum'
? mnemonicToLegacySeed(phrase, '', false, 64)
: mnemonicToMiniSecret(phrase, password);
} else {
assert(str.length <= 32, 'specified phrase is not a valid mnemonic and is invalid as a raw seed at > 32 bytes');
assert(phrase.length <= 32, 'specified phrase is not a valid mnemonic and is invalid as a raw seed at > 32 bytes');
seed = stringToU8a(str.padEnd(32));
seed = stringToU8a(phrase.padEnd(32));
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/keyring', version: '7.3.1' };
export const packageInfo = { name: '@polkadot/keyring', version: '7.5.1' };
+1 -1
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { EncryptedJsonEncoding } from '@polkadot/util-crypto/json/types';
import type { EncryptedJsonEncoding } from '@polkadot/util-crypto/types';
import type { PairInfo } from './types';
import { assert, isUndefined, u8aEq } from '@polkadot/util';
+12 -10
View File
@@ -1,8 +1,8 @@
// Copyright 2017-2021 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { EncryptedJsonEncoding } from '@polkadot/util-crypto/json/types';
import type { Keypair, KeypairType } from '@polkadot/util-crypto/types';
import type { HexString } from '@polkadot/util/types';
import type { EncryptedJsonEncoding, Keypair, KeypairType } from '@polkadot/util-crypto/types';
import type { KeyringPair, KeyringPair$Json, KeyringPair$Meta, SignOptions } from '../types';
import type { PairInfo } from './types';
@@ -145,13 +145,15 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
},
// eslint-disable-next-line sort-keys
decodePkcs8,
decryptMessage: (encryptedMessageWithNonce: string | Uint8Array, senderPublicKey: string | Uint8Array): Uint8Array | null => {
decryptMessage: (encryptedMessageWithNonce: HexString | string | Uint8Array, senderPublicKey: HexString | string | Uint8Array): Uint8Array | null => {
assert(!isLocked(secretKey), 'Cannot encrypt with a locked key pair');
assert(!['ecdsa', 'ethereum'].includes(type), 'Secp256k1 not supported yet');
const messageU8a = u8aToU8a(encryptedMessageWithNonce);
return naclOpen(
u8aToU8a(encryptedMessageWithNonce.slice(24, encryptedMessageWithNonce.length)),
u8aToU8a(encryptedMessageWithNonce.slice(0, 24)),
messageU8a.slice(24, messageU8a.length),
messageU8a.slice(0, 24),
convertPublicKeyToCurve25519(u8aToU8a(senderPublicKey)),
convertSecretKeyToCurve25519(secretKey)
);
@@ -168,7 +170,7 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
encodePkcs8: (passphrase?: string): Uint8Array => {
return recode(passphrase);
},
encryptMessage: (message: string | Uint8Array, recipientPublicKey: string | Uint8Array, nonceIn?: Uint8Array): Uint8Array => {
encryptMessage: (message: HexString | string | Uint8Array, recipientPublicKey: HexString | string | Uint8Array, nonceIn?: Uint8Array): Uint8Array => {
assert(!isLocked(secretKey), 'Cannot encrypt with a locked key pair');
assert(!['ecdsa', 'ethereum'].includes(type), 'Secp256k1 not supported yet');
@@ -182,7 +184,7 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
setMeta: (additional: KeyringPair$Meta): void => {
meta = { ...meta, ...additional };
},
sign: (message: string | Uint8Array, options: SignOptions = {}): Uint8Array => {
sign: (message: HexString | string | Uint8Array, options: SignOptions = {}): Uint8Array => {
assert(!isLocked(secretKey), 'Cannot sign with a locked key pair');
return u8aConcat(
@@ -207,10 +209,10 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
unlock: (passphrase?: string): void => {
return decodePkcs8(passphrase);
},
verify: (message: string | Uint8Array, signature: Uint8Array, signerPublic: string | Uint8Array): boolean => {
verify: (message: HexString | string | Uint8Array, signature: HexString | string | Uint8Array, signerPublic: HexString | string | Uint8Array): boolean => {
return signatureVerify(message, signature, TYPE_ADDRESS[type](u8aToU8a(signerPublic))).isValid;
},
vrfSign: (message: string | Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): Uint8Array => {
vrfSign: (message: HexString | string | Uint8Array, context?: HexString | string | Uint8Array, extra?: string | Uint8Array): Uint8Array => {
assert(!isLocked(secretKey), 'Cannot sign with a locked key pair');
if (type === 'sr25519') {
@@ -221,7 +223,7 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
return u8aConcat(vrfHash(proof, context, extra), proof);
},
vrfVerify: (message: string | Uint8Array, vrfResult: Uint8Array, signerPublic: Uint8Array | string, context?: string | Uint8Array, extra?: string | Uint8Array): boolean => {
vrfVerify: (message: HexString | string | Uint8Array, vrfResult: Uint8Array, signerPublic: HexString | Uint8Array | string, context?: HexString | string | Uint8Array, extra?: HexString | string | Uint8Array): boolean => {
if (type === 'sr25519') {
return schnorrkelVrfVerify(message, vrfResult, publicKey, context, extra);
}
+50 -48
View File
@@ -7,10 +7,12 @@ import { encodeAddress } from '@polkadot/util-crypto';
const publicKey = new Uint8Array(32);
const address = encodeAddress(publicKey);
const meta = {
isTesting: true,
name: 'nobody'
};
const json: KeyringPair$Json = {
address,
encoded: '',
@@ -22,54 +24,54 @@ const json: KeyringPair$Json = {
meta
};
export function nobody (): KeyringPair {
const pair: KeyringPair = {
address,
addressRaw: publicKey,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
decodePkcs8: (passphrase?: string, encoded?: Uint8Array): void =>
undefined,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
decryptMessage: (encryptedMessageWithNonce: string | Uint8Array, senderPublicKey: string | Uint8Array): Uint8Array | null =>
null,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
derive: (suri: string, meta?: KeyringPair$Meta): KeyringPair =>
pair,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
encodePkcs8: (passphrase?: string): Uint8Array =>
new Uint8Array(0),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
encryptMessage: (message: string | Uint8Array, recipientPublicKey: string | Uint8Array, _nonce?: Uint8Array): Uint8Array =>
new Uint8Array(),
isLocked: true,
lock: (): void => {
// no locking, it is always locked
},
meta,
publicKey,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
setMeta: (meta: KeyringPair$Meta): void =>
undefined,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
sign: (message: Uint8Array): Uint8Array =>
new Uint8Array(64),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
toJson: (passphrase?: string): KeyringPair$Json =>
json,
type: 'ed25519',
// eslint-disable-next-line @typescript-eslint/no-unused-vars
unlock: (passphrase?: string): void =>
undefined,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
verify: (message: Uint8Array, signature: Uint8Array): boolean =>
false,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
vrfSign: (message: Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): Uint8Array =>
new Uint8Array(96),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
vrfVerify: (message: Uint8Array, vrfResult: Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): boolean =>
false
};
const pair: KeyringPair = {
address,
addressRaw: publicKey,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
decodePkcs8: (passphrase?: string, encoded?: Uint8Array): void =>
undefined,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
decryptMessage: (encryptedMessageWithNonce: string | Uint8Array, senderPublicKey: string | Uint8Array): Uint8Array | null =>
null,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
derive: (suri: string, meta?: KeyringPair$Meta): KeyringPair =>
pair,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
encodePkcs8: (passphrase?: string): Uint8Array =>
new Uint8Array(0),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
encryptMessage: (message: string | Uint8Array, recipientPublicKey: string | Uint8Array, _nonce?: Uint8Array): Uint8Array =>
new Uint8Array(),
isLocked: true,
lock: (): void => {
// no locking, it is always locked
},
meta,
publicKey,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
setMeta: (meta: KeyringPair$Meta): void =>
undefined,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
sign: (message: Uint8Array): Uint8Array =>
new Uint8Array(64),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
toJson: (passphrase?: string): KeyringPair$Json =>
json,
type: 'ed25519',
// eslint-disable-next-line @typescript-eslint/no-unused-vars
unlock: (passphrase?: string): void =>
undefined,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
verify: (message: Uint8Array, signature: Uint8Array): boolean =>
false,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
vrfSign: (message: Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): Uint8Array =>
new Uint8Array(96),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
vrfVerify: (message: Uint8Array, vrfResult: Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): boolean =>
false
};
export function nobody (): KeyringPair {
return pair;
}
+3 -2
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { KeyringPair, KeyringPairs } from './types';
import { assert, isHex, isU8a, u8aToHex, u8aToU8a } from '@polkadot/util';
@@ -21,7 +22,7 @@ export class Pairs implements KeyringPairs {
return Object.values(this.#map);
}
public get (address: string | Uint8Array): KeyringPair {
public get (address: HexString | string | Uint8Array): KeyringPair {
const pair = this.#map[decodeAddress(address).toString()];
assert(pair, () => `Unable to retrieve keypair '${
@@ -33,7 +34,7 @@ export class Pairs implements KeyringPairs {
return pair;
}
public remove (address: string | Uint8Array): void {
public remove (address: HexString | string | Uint8Array): void {
delete this.#map[decodeAddress(address).toString()];
}
}
+21 -8
View File
@@ -3,12 +3,15 @@
// From https://github.com/paritytech/substrate/wiki/Secret-URI-Test-Vectors
import type { KeypairType } from '@polkadot/util-crypto/types';
import { u8aToHex } from '@polkadot/util';
import { cryptoWaitReady } from '@polkadot/util-crypto';
import Keyring from '.';
const PHRASE = 'bottom drive obey lake curtain smoke basket hold race lonely fit walk';
const ETHEREUM_PHRASE = 'seed sock milk update focus rotate barely fade car face mechanic mercy';
const TESTS = {
ecdsa: [
@@ -22,7 +25,17 @@ const TESTS = {
{
pk: '0x0381351b1b46d2602b0992bb5d5531f9c1696b0812feb2534b6884adc47e2e1d8b',
ss: '0x31ea8795EE32D782C8ff41a5C68Dcbf0F5B27f6d',
uri: "seed sock milk update focus rotate barely fade car face mechanic mercy/m/44'/60'/0'/0/0"
uri: `${ETHEREUM_PHRASE}/m/44'/60'/0'/0/0`
},
{
pk: '0x02509540919faacf9ab52146c9aa40db68172d83777250b28e4679176e49ccdd9f',
ss: '0xf24FF3a9CF04c71Dbc94D0b566f7A27B94566cac',
uri: `${PHRASE}/m/44'/60'/0'/0/0`
},
{
pk: '0x033bc19e36ff1673910575b6727a974a9abd80c9a875d41ab3e2648dbfb9e4b518',
ss: '0x3Cd0A705a2DC65e5b1E1205896BaA2be8A07c6e0',
uri: `${PHRASE}/m/44'/60'/0'/0/1`
}
],
sr25519: [
@@ -75,17 +88,17 @@ const TESTS = {
};
describe('keyring.addFromUri', (): void => {
const keyring = new Keyring({ type: 'sr25519' });
beforeEach(async (): Promise<void> => {
await cryptoWaitReady();
});
Object.entries(TESTS).forEach(([type, tests]): void => {
const keyring = new Keyring({ type: type as KeypairType });
beforeEach(async (): Promise<void> => {
await cryptoWaitReady();
});
describe(type, (): void => {
tests.forEach(({ pk, ss, uri }): void => {
it(`creates ${uri}`, (): void => {
const pair = keyring.addFromUri(uri, {}, type as 'sr25519');
const pair = keyring.addFromUri(uri, {}, type as KeypairType);
expect(u8aToHex(pair.publicKey)).toEqual(pk);
expect(pair.address).toEqual(ss);
+7 -9
View File
@@ -12,7 +12,7 @@ import { createPair } from './pair';
interface PairDef {
name?: string;
publicKey: Uint8Array;
seed: string;
seed?: string;
secretKey?: Uint8Array;
type: KeypairType
}
@@ -77,42 +77,36 @@ export const PAIRSETHEREUM: PairDef[] = [
name: 'Alith',
publicKey: hexToU8a('0x02509540919faacf9ab52146c9aa40db68172d83777250b28e4679176e49ccdd9f'),
secretKey: hexToU8a('0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133'), // nosemgrep
seed: "m/44'/40'/0'/0",
type: 'ethereum'
},
{
name: 'Baltathar',
publicKey: hexToU8a('0x033bc19e36ff1673910575b6727a974a9abd80c9a875d41ab3e2648dbfb9e4b518'),
secretKey: hexToU8a('0x8075991ce870b93a8870eca0c0f91913d12f47948ca0fd25b49c6fa7cdbeee8b'), // nosemgrep
seed: "m/44'/40'/0'/0",
type: 'ethereum'
},
{
name: 'Charleth',
publicKey: hexToU8a('0x0234637bdc0e89b5d46543bcbf8edff329d2702bc995e27e9af4b1ba009a3c2a5e'),
secretKey: hexToU8a('0x0b6e18cafb6ed99687ec547bd28139cafdd2bffe70e6b688025de6b445aa5c5b'), // nosemgrep
seed: "m/44'/40'/0'/0",
type: 'ethereum'
},
{
name: 'Dorothy',
publicKey: hexToU8a('0x02a00d60b2b408c2a14c5d70cdd2c205db8985ef737a7e55ad20ea32cc9e7c417c'),
secretKey: hexToU8a('0x39539ab1876910bbf3a223d84a29e28f1cb4e2e456503e7e91ed39b2e7223d68'), // nosemgrep
seed: "m/44'/40'/0'/0",
type: 'ethereum'
},
{
name: 'Ethan',
publicKey: hexToU8a('0x025cdc005b752651cd3f728fb9192182acb3a9c89e19072cbd5b03f3ee1f1b3ffa'),
secretKey: hexToU8a('0x7dce9bc8babb68fec1409be38c8e1a52650206a7ed90ff956ae8a6d15eeaaef4'), // nosemgrep
seed: "m/44'/40'/0'/0",
type: 'ethereum'
},
{
name: 'Faith',
publicKey: hexToU8a('0x037964b6c9d546da4646ada28a99e34acaa1d14e7aba861a9055f9bd200c8abf74'),
secretKey: hexToU8a('0xb9d2ea9a615f3165812e8d44de0d24da9bbd164b65c4f0573e1ce2c8dbd9c8df'), // nosemgrep
seed: "m/44'/40'/0'/0",
type: 'ethereum'
}
];
@@ -128,11 +122,15 @@ export function createTestKeyring (options: KeyringOptions = {}, isDerived = tru
const pairs: PairDef[] = (options.type && options.type === 'ethereum') ? PAIRSETHEREUM : PAIRSSR25519;
pairs.forEach(({ name, publicKey, secretKey, seed, type }): void => {
if (!name && !seed) {
throw new Error('Testing pair should have either a name or a seed');
}
const meta = {
isTesting: true,
name: name || seed.replace('//', '_').toLowerCase()
name: name || (seed && seed.replace('//', '_').toLowerCase())
};
const pair = !isDerived && !name
const pair = !isDerived && !name && seed
? keyring.addFromUri(seed, meta, options.type)
: keyring.addPair(
createPair({ toSS58: keyring.encodeAddress, type }, { publicKey, secretKey }, meta)
+9 -10
View File
@@ -1,9 +1,8 @@
// Copyright 2017-2021 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Prefix } from '@polkadot/util-crypto/address/types';
import type { EncryptedJson } from '@polkadot/util-crypto/json/types';
import type { Keypair, KeypairType } from '@polkadot/util-crypto/types';
import type { HexString } from '@polkadot/util/types';
import type { EncryptedJson, Keypair, KeypairType, Prefix } from '@polkadot/util-crypto/types';
export interface KeyringOptions {
ss58Format?: Prefix;
@@ -13,7 +12,7 @@ export interface KeyringOptions {
export type KeyringPair$Meta = Record<string, unknown>;
export interface KeyringPair$Json extends EncryptedJson {
address: string;
address: string | HexString;
meta: KeyringPair$Meta;
}
@@ -34,14 +33,14 @@ export interface KeyringPair {
encodePkcs8 (passphrase?: string): Uint8Array;
lock (): void;
setMeta (meta: KeyringPair$Meta): void;
sign (message: string | Uint8Array, options?: SignOptions): Uint8Array;
sign (message: HexString | string | Uint8Array, options?: SignOptions): Uint8Array;
toJson (passphrase?: string): KeyringPair$Json;
unlock (passphrase?: string): void;
encryptMessage (message: string | Uint8Array, recipientPublicKey: string | Uint8Array, nonce?: Uint8Array): Uint8Array;
decryptMessage (encryptedMessageWithNonce: string | Uint8Array, senderPublicKey: string | Uint8Array): Uint8Array | null;
verify (message: string | Uint8Array, signature: Uint8Array, signerPublic: string | Uint8Array): boolean;
vrfSign (message: string | Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): Uint8Array;
vrfVerify (message: string | Uint8Array, vrfResult: Uint8Array, signerPublic: Uint8Array | string, context?: string | Uint8Array, extra?: string | Uint8Array): boolean;
encryptMessage (message: HexString | string | Uint8Array, recipientPublicKey: HexString | string | Uint8Array, nonce?: Uint8Array): Uint8Array;
decryptMessage (encryptedMessageWithNonce: HexString | string | Uint8Array, senderPublicKey: HexString | string | Uint8Array): Uint8Array | null;
verify (message: HexString | string | Uint8Array, signature: Uint8Array, signerPublic: HexString | string | Uint8Array): boolean;
vrfSign (message: HexString | string | Uint8Array, context?: HexString | string | Uint8Array, extra?: HexString | string | Uint8Array): Uint8Array;
vrfVerify (message: HexString | string | Uint8Array, vrfResult: Uint8Array, signerPublic: HexString | Uint8Array | string, context?: HexString | string | Uint8Array, extra?: HexString | string | Uint8Array): boolean;
}
export interface KeyringPairs {
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/networks",
"version": "7.3.1",
"version": "7.5.1",
"type": "module",
"description": "A list of all available Substrate networks and their applicable prefixes",
"main": "index.js",
@@ -16,10 +16,10 @@
"bugs": "https://github.com/polkadot-js/common/issues",
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/networks#readme",
"dependencies": {
"@babel/runtime": "^7.15.3"
"@babel/runtime": "^7.15.4"
},
"devDependencies": {
"@polkadot/util": "7.3.1",
"@polkadot/x-fetch": "7.3.1"
"@polkadot/util": "7.5.1",
"@polkadot/x-fetch": "7.5.1"
}
}
+6 -3
View File
@@ -6,11 +6,14 @@ import fetch from 'node-fetch';
const SUBSTRATE_REGISTRY = 'https://raw.githubusercontent.com/paritytech/substrate/master/ss58-registry.json';
function outputField (v) {
function outputField (k, v) {
if (typeof v === 'string') {
return `'${v}'`;
} else if (Array.isArray(v)) {
return `[${v.map((v) => outputField(v)).join(', ')}]`;
// new format is [] to indicate optionality
return (['decimals', 'symbols'].includes(k) && !v.length)
? null
: `[${v.map((v) => outputField(k, v)).join(', ')}]`;
}
return v;
@@ -25,7 +28,7 @@ async function getSubstrateRegistry () {
` {\n${Object
.entries(e)
.sort(([a], [b]) => a.localeCompare(b))
.map(([k, v]) => ` ${k}: ${outputField(v)}`)
.map(([k, v]) => ` ${k}: ${outputField(k, v)}`)
.join(',\n')}\n }`
)
.join(',\n');
+5 -1
View File
@@ -60,7 +60,11 @@ describe('check latest Substrate ss58 registry', (): void => {
return [
`${n.displayName} (${n.prefix})`,
other
? fields.filter((f) => stringify(n[f]) !== stringify(other[f]))
? fields.filter((f) =>
['decimals', 'symbols'].includes(f)
? stringify(n[f] || []) !== stringify(other[f] || [])
: stringify(n[f]) !== stringify(other[f])
)
: []
];
})
+1 -1
View File
@@ -18,7 +18,7 @@ export const allNetworks = knownSubstrate.map((o): SubstrateNetwork => {
n.genesisHash = knownGenesis[network] || [];
n.icon = knownIcon[network] || 'substrate';
n.isIgnored = !network || !!knownTestnet[network] || network.startsWith('reserved');
n.isIgnored = !network || !!knownTestnet[network] || !o.standardAccount;
return n;
});
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/networks', version: '7.3.1' };
export const packageInfo = { name: '@polkadot/networks', version: '7.5.1' };
+55 -1
View File
@@ -387,7 +387,7 @@ export const knownSubstrate: KnownSubstrate[] = [
prefix: 42,
standardAccount: '*25519',
symbols: null,
website: 'https://substrate.dev/'
website: 'https://docs.substrate.io/'
},
{
decimals: null,
@@ -443,6 +443,24 @@ export const knownSubstrate: KnownSubstrate[] = [
symbols: ['NEAT'],
website: 'https://neatcoin.org'
},
{
decimals: [12],
displayName: 'Picasso',
network: 'picasso',
prefix: 49,
standardAccount: '*25519',
symbols: ['PICA'],
website: 'https://picasso.composable.finance'
},
{
decimals: [12],
displayName: 'Composable',
network: 'composable',
prefix: 50,
standardAccount: '*25519',
symbols: ['LAYR'],
website: 'https://composable.finance'
},
{
decimals: [12],
displayName: 'HydraDX',
@@ -515,6 +533,15 @@ export const knownSubstrate: KnownSubstrate[] = [
symbols: ['KMA'],
website: 'https://manta.network'
},
{
decimals: [12],
displayName: 'Polkadex Mainnet',
network: 'polkadex',
prefix: 88,
standardAccount: '*25519',
symbols: ['PDEX'],
website: 'https://polkadex.trade'
},
{
decimals: [18],
displayName: 'PolkaSmith Canary Network',
@@ -560,6 +587,15 @@ export const knownSubstrate: KnownSubstrate[] = [
symbols: null,
website: 'https://integritee.network'
},
{
decimals: [18],
displayName: 'Clover Finance',
network: 'clover',
prefix: 128,
standardAccount: '*25519',
symbols: ['CLV'],
website: 'https://clover.finance'
},
{
decimals: [18],
displayName: 'Altair',
@@ -605,6 +641,15 @@ export const knownSubstrate: KnownSubstrate[] = [
symbols: ['MOVR'],
website: 'https://moonbeam.network'
},
{
decimals: [18],
displayName: 'Automata Mainnet',
network: 'automata',
prefix: 2349,
standardAccount: '*25519',
symbols: ['ATA'],
website: 'https://ata.network'
},
{
decimals: [12],
displayName: 'Basilisk',
@@ -613,5 +658,14 @@ export const knownSubstrate: KnownSubstrate[] = [
standardAccount: '*25519',
symbols: ['BSX'],
website: 'https://bsx.fi'
},
{
decimals: [18],
displayName: 'Automata ContextFree',
network: 'contextfree',
prefix: 11820,
standardAccount: '*25519',
symbols: ['CTX'],
website: 'https://ata.network'
}
];
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/util-crypto",
"version": "7.3.1",
"version": "7.5.1",
"type": "module",
"description": "A collection of useful crypto utilities for @polkadot",
"main": "index.js",
@@ -21,11 +21,11 @@
"bugs": "https://github.com/polkadot-js/common/issues",
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util-crypto#readme",
"dependencies": {
"@babel/runtime": "^7.15.3",
"@polkadot/networks": "7.3.1",
"@polkadot/util": "7.3.1",
"@babel/runtime": "^7.15.4",
"@polkadot/networks": "7.5.1",
"@polkadot/util": "7.5.1",
"@polkadot/wasm-crypto": "^4.2.1",
"@polkadot/x-randomvalues": "7.3.1",
"@polkadot/x-randomvalues": "7.5.1",
"base-x": "^3.0.8",
"base64-js": "^1.5.1",
"blakejs": "^1.1.1",
@@ -47,6 +47,6 @@
"@types/xxhashjs": "^0.2.2"
},
"peerDependencies": {
"@polkadot/util": "7.3.1"
"@polkadot/util": "7.5.1"
}
}
@@ -1,13 +1,15 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { decodeAddress } from './decode';
/**
* @name addressToEvm
* @summary Converts an SS58 address to its corresponding EVM address.
*/
export function addressToEvm (address: string | Uint8Array, ignoreChecksum?: boolean): Uint8Array {
export function addressToEvm (address: HexString | string | Uint8Array, ignoreChecksum?: boolean): Uint8Array {
const decoded = decodeAddress(address, ignoreChecksum);
return decoded.subarray(0, 20);
+2 -1
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types';
import { base58Decode } from '../base58/decode';
@@ -13,7 +14,7 @@ import { defaults } from './defaults';
* @description
* From the provided input, validate that the address is a valid input.
*/
export function checkAddress (address: string, prefix: Prefix): [boolean, string | null] {
export function checkAddress (address: HexString | string, prefix: Prefix): [boolean, string | null] {
let decoded;
try {
+3 -2
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types';
// Original implementation: https://github.com/paritytech/polka-ui/blob/4858c094684769080f5811f32b081dd7780b0880/src/polkadot.js#L6
@@ -10,7 +11,7 @@ import { base58Decode } from '../base58/decode';
import { checkAddressChecksum } from './checksum';
import { defaults } from './defaults';
export function decodeAddress (encoded?: string | Uint8Array | null, ignoreChecksum?: boolean, ss58Format: Prefix = -1): Uint8Array {
export function decodeAddress (encoded?: HexString | string | Uint8Array | null, ignoreChecksum?: boolean, ss58Format: Prefix = -1): Uint8Array {
assert(encoded, 'Invalid empty address passed');
if (isU8a(encoded) || isHex(encoded)) {
@@ -29,6 +30,6 @@ export function decodeAddress (encoded?: string | Uint8Array | null, ignoreCheck
return decoded.slice(ss58Length, endPos);
} catch (error) {
throw new Error(`Decoding ${encoded as string}: ${(error as Error).message}`);
throw new Error(`Decoding ${encoded}: ${(error as Error).message}`);
}
}
+2 -1
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types';
import { assert } from '@polkadot/util';
@@ -17,7 +18,7 @@ import { encodeAddress } from './encode';
* @description
* Creates a sr25519 derived address based on the input address/publicKey and the uri supplied.
*/
export function deriveAddress (who: Uint8Array | string, suri: string, ss58Format?: Prefix): string {
export function deriveAddress (who: HexString | Uint8Array | string, suri: string, ss58Format?: Prefix): string {
const { path } = keyExtractPath(suri);
assert(path.length && !path.some((path) => path.isHard), 'Expected suri to contain a combination of non-hard paths');
+2 -1
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types';
// Original implementation: https://github.com/paritytech/polka-ui/blob/4858c094684769080f5811f32b081dd7780b0880/src/polkadot.js#L34
@@ -11,7 +12,7 @@ import { decodeAddress } from './decode';
import { defaults } from './defaults';
import { sshash } from './sshash';
export function encodeAddress (key: Uint8Array | string, ss58Format: Prefix = defaults.prefix): string {
export function encodeAddress (key: HexString | Uint8Array | string, ss58Format: Prefix = defaults.prefix): string {
// decode it, this means we can re-encode an address
const u8a = decodeAddress(key);
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types';
import { decodeAddress } from './decode';
@@ -14,6 +15,6 @@ import { createKeyDerived } from './keyDerived';
* @description
* Creates a Substrate derived address based on the input address/publicKey and the index supplied.
*/
export function encodeDerivedAddress (who: Uint8Array | string, index: bigint | BN | number, ss58Format?: Prefix): string {
export function encodeDerivedAddress (who: HexString | Uint8Array | string, index: bigint | BN | number, ss58Format?: Prefix): string {
return encodeAddress(createKeyDerived(decodeAddress(who), index), ss58Format);
}
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types';
import { encodeAddress } from './encode';
@@ -13,6 +14,6 @@ import { createKeyMulti } from './keyMulti';
* @description
* Creates a Substrate multisig address based on the input address and the required threshold.
*/
export function encodeMultiAddress (who: (Uint8Array | string)[], threshold: bigint | BN | number, ss58Format?: Prefix): string {
export function encodeMultiAddress (who: (HexString | Uint8Array | string)[], threshold: bigint | BN | number, ss58Format?: Prefix): string {
return encodeAddress(createKeyMulti(who, threshold), ss58Format);
}
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aEq } from '@polkadot/util';
import { decodeAddress } from './decode';
@@ -19,6 +21,6 @@ import { decodeAddress } from './decode';
* u8aEq(new Uint8Array([0x68, 0x65]), new Uint8Array([0x68, 0x65])); // true
* ```
*/
export function addressEq (a: string | Uint8Array, b: string | Uint8Array): boolean {
export function addressEq (a: HexString | string | Uint8Array, b: HexString | string | Uint8Array): boolean {
return u8aEq(decodeAddress(a), decodeAddress(b));
}
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { HashType } from '../secp256k1/types';
import type { Prefix } from './types';
@@ -13,7 +14,7 @@ import { encodeAddress } from './encode';
* @name evmToAddress
* @summary Converts an EVM address to its corresponding SS58 address.
*/
export function evmToAddress (evmAddress: string | Uint8Array, ss58Format?: Prefix, hashType: HashType = 'blake2'): string {
export function evmToAddress (evmAddress: HexString | string | Uint8Array, ss58Format?: Prefix, hashType: HashType = 'blake2'): string {
const wrapError = (message: string) => `Converting ${evmAddress as string}: ${message}`;
const message = u8aConcat('evm:', evmAddress);
+2 -1
View File
@@ -1,11 +1,12 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types';
import { validateAddress } from './validate';
export function isAddress (address?: string | null, ignoreChecksum?: boolean, ss58Format?: Prefix): address is string {
export function isAddress (address?: HexString | string | null, ignoreChecksum?: boolean, ss58Format?: Prefix): address is string {
try {
return validateAddress(address, ignoreChecksum, ss58Format);
} catch (error) {
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import { bnToU8a, stringToU8a, u8aConcat } from '@polkadot/util';
@@ -10,7 +11,7 @@ import { decodeAddress } from './decode';
const PREFIX = stringToU8a('modlpy/utilisuba');
export function createKeyDerived (who: Uint8Array | string, index: bigint | BN | number): Uint8Array {
export function createKeyDerived (who: HexString | Uint8Array | string, index: bigint | BN | number): Uint8Array {
return blake2AsU8a(
u8aConcat(
PREFIX,
+2 -1
View File
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import { bnToU8a, compactToU8a, stringToU8a, u8aConcat, u8aSorted } from '@polkadot/util';
@@ -10,7 +11,7 @@ import { decodeAddress } from './decode';
const PREFIX = stringToU8a('modlpy/utilisuba');
export function createKeyMulti (who: (Uint8Array | string)[], threshold: bigint | BN | number): Uint8Array {
export function createKeyMulti (who: (HexString | Uint8Array | string)[], threshold: bigint | BN | number): Uint8Array {
return blake2AsU8a(
u8aConcat(
PREFIX,
+2 -1
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types';
import { u8aSorted } from '@polkadot/util';
@@ -8,7 +9,7 @@ import { u8aSorted } from '@polkadot/util';
import { decodeAddress } from './decode';
import { encodeAddress } from './encode';
export function sortAddresses (addresses: (Uint8Array | string)[], ss58Format?: Prefix): string[] {
export function sortAddresses (addresses: (HexString | Uint8Array | string)[], ss58Format?: Prefix): string[] {
return u8aSorted(
addresses.map((who) => decodeAddress(who))
).map((u8a) => encodeAddress(u8a, ss58Format));
+2 -1
View File
@@ -1,10 +1,11 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types';
import { decodeAddress } from './decode';
export function validateAddress (encoded?: string | null, ignoreChecksum?: boolean, ss58Format?: Prefix): encoded is string {
export function validateAddress (encoded?: HexString | string | null, ignoreChecksum?: boolean, ss58Format?: Prefix): encoded is string {
return !!decodeAddress(encoded, ignoreChecksum, ss58Format);
}
+3 -1
View File
@@ -3,6 +3,8 @@
// adapted from https://github.com/multiformats/js-multibase/blob/424709195b46ffb1d6f2f69a7707598ebe751e5e/src/rfc4648.js
import type { U8aLike } from '@polkadot/util/types';
import { u8aToU8a } from '@polkadot/util';
import { BASE32_ALPHABET, BITS_PER_CHAR } from './bs32';
@@ -15,7 +17,7 @@ const MASK = (1 << BITS_PER_CHAR) - 1;
* @description
* From the provided input, create the base32 and return the result as a string.
*/
export function base32Encode (value: Uint8Array | string | Buffer | number[], ipfsCompat = false): string {
export function base32Encode (value: U8aLike, ipfsCompat = false): string {
const u8a = u8aToU8a(value);
let out = '';
let bits = 0;
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { U8aLike } from '@polkadot/util/types';
import { u8aToU8a } from '@polkadot/util';
import { bs58 } from './bs58';
@@ -11,7 +13,7 @@ import { bs58 } from './bs58';
* @description
* From the provided input, create the base58 and return the result as a string.
*/
export function base58Encode (value: Uint8Array | string | Buffer | number[], ipfsCompat?: boolean): string {
export function base58Encode (value: U8aLike, ipfsCompat?: boolean): string {
const out = bs58.encode(u8aToU8a(value));
return ipfsCompat
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { U8aLike } from '@polkadot/util/types';
import base64 from 'base64-js';
import { u8aToU8a } from '@polkadot/util';
@@ -11,6 +13,6 @@ import { u8aToU8a } from '@polkadot/util';
* @description
* From the provided input, create the base64 and return the result as a string.
*/
export function base64Encode (value: Uint8Array | string | Buffer | number[]): string {
export function base64Encode (value: U8aLike): string {
return base64.fromByteArray(u8aToU8a(value));
}
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aToHex } from '@polkadot/util';
import { blake2AsU8a } from './asU8a';
@@ -19,7 +21,7 @@ import { blake2AsU8a } from './asU8a';
* blake2AsHex('abc'); // => 0xba80a53f981c4d0d
* ```
*/
export function blake2AsHex (data: Uint8Array | string, bitLength = 256, key?: Uint8Array | null, onlyJs = false): string {
export function blake2AsHex (data: HexString | Uint8Array | string, bitLength = 256, key?: Uint8Array | null, onlyJs = false): HexString {
return u8aToHex(
blake2AsU8a(data, bitLength, key, onlyJs)
);
+4 -2
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import js from 'blakejs';
import { u8aToU8a } from '@polkadot/util';
@@ -17,10 +19,10 @@ import { blake2b, isReady } from '@polkadot/wasm-crypto';
* ```javascript
* import { blake2AsU8a } from '@polkadot/util-crypto';
*
* blake2AsU8a('abc'); // => [0xba, 0x80, 0xa53, 0xf98, 0x1c, 0x4d, 0x0d]
* blake2AsU8a('abc'); // => [0xba, 0x80, 0xa5, 0x3f, 0x98, 0x1c, 0x4d, 0x0d]
* ```
*/
export function blake2AsU8a (data: Uint8Array | string, bitLength = 256, key?: Uint8Array | null, onlyJs = false): Uint8Array {
export function blake2AsU8a (data: HexString | Uint8Array | string, bitLength = 256, key?: Uint8Array | null, onlyJs = false): Uint8Array {
const byteLength = Math.ceil(bitLength / 8);
return isReady() && !onlyJs
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { assert, u8aToHex, u8aToU8a } from '@polkadot/util';
import { keccakAsU8a } from '../keccak';
@@ -14,7 +16,7 @@ function getH160 (u8a: Uint8Array): Uint8Array {
return u8a.slice(-20);
}
export function ethereumEncode (addressOrPublic?: string | Uint8Array): string {
export function ethereumEncode (addressOrPublic?: HexString | string | Uint8Array): HexString {
if (!addressOrPublic) {
return '0x';
}
@@ -1,11 +1,13 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { isHex } from '@polkadot/util';
import { isEthereumChecksum } from './isChecksum';
export function isEthereumAddress (address?: string): boolean {
export function isEthereumAddress (address?: HexString | string): boolean {
if (!address || address.length !== 42 || !isHex(address)) {
return false;
} else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) {
+14
View File
@@ -0,0 +1,14 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import hash from 'hash.js';
export function hmacSha (key: Uint8Array | string, data: Uint8Array, is512: boolean): Uint8Array {
return Uint8Array.from(
hash
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
.hmac(is512 ? hash.sha512 : hash.sha256, key)
.update(data)
.digest());
}
+2 -8
View File
@@ -1,14 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import hash from 'hash.js';
import { hmacSha } from './sha';
export function hmacSha256 (key: Uint8Array | string, data: Uint8Array): Uint8Array {
return Uint8Array.from(
hash
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
.hmac(hash.sha256, key)
.update(data)
.digest());
return hmacSha(key, data, false);
}
+2 -8
View File
@@ -1,14 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import hash from 'hash.js';
import { hmacSha } from './sha';
export function hmacSha512 (key: Uint8Array | string, data: Uint8Array): Uint8Array {
return Uint8Array.from(
hash
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
.hmac(hash.sha512, key)
.update(data)
.digest());
return hmacSha(key, data, true);
}
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
export type EncryptedJsonVersion = '0' | '1' | '2' | '3';
export type EncryptedJsonEncoding = 'none' | 'scrypt' | 'xsalsa20-poly1305';
@@ -12,6 +14,6 @@ export interface EncryptedJsonDescriptor {
}
export interface EncryptedJson {
encoded: string;
encoded: HexString | string;
encoding: EncryptedJsonDescriptor;
}
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aToHex } from '@polkadot/util';
import { keccakAsU8a } from './asU8a';
@@ -19,7 +21,7 @@ import { keccakAsU8a } from './asU8a';
* keccakAsHex('123'); // => 0x...
* ```
*/
export function keccakAsHex (value: Buffer | Uint8Array | string, bitLength?: 256 | 512): string {
export function keccakAsHex (value: HexString | Buffer | Uint8Array | string, bitLength?: 256 | 512): HexString {
return u8aToHex(
keccakAsU8a(value, bitLength)
);
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import js from 'js-sha3';
import { u8aToU8a } from '@polkadot/util';
@@ -20,7 +22,7 @@ import { isReady, keccak256 } from '@polkadot/wasm-crypto';
* keccakAsU8a('123'); // => Uint8Array
* ```
*/
export function keccakAsU8a (value: Buffer | Uint8Array | string, bitLength: 256 | 512 = 256, onlyJs = false): Uint8Array {
export function keccakAsU8a (value: HexString | Buffer | Uint8Array | string, bitLength: 256 | 512 = 256, onlyJs = false): Uint8Array {
const is256 = bitLength === 256;
return isReady() && is256 && !onlyJs
@@ -1,7 +1,9 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { BN, bnToHex, compactAddLength, hexToU8a, isBigInt, isBn, isHex, isNumber, isString, stringToU8a } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import { BN, bnToU8a, compactAddLength, hexToU8a, isBigInt, isBn, isHex, isNumber, isString, stringToU8a } from '@polkadot/util';
import { blake2AsU8a } from '../blake2/asU8a';
@@ -26,7 +28,7 @@ export class DeriveJunction {
result.soft(
RE_NUMBER.test(code)
? parseInt(code, 10)
? new BN(code, 10)
: code
);
@@ -47,7 +49,7 @@ export class DeriveJunction {
return !this.#isHard;
}
public hard (value: number | string | bigint | BN | Uint8Array): DeriveJunction {
public hard (value: HexString | number | string | bigint | BN | Uint8Array): DeriveJunction {
return this.soft(value).harden();
}
@@ -57,9 +59,9 @@ export class DeriveJunction {
return this;
}
public soft (value: number | string | bigint | BN | Uint8Array): DeriveJunction {
public soft (value: HexString | number | string | bigint | BN | Uint8Array): DeriveJunction {
if (isNumber(value) || isBn(value) || isBigInt(value)) {
return this.soft(bnToHex(value, BN_OPTIONS));
return this.soft(bnToU8a(value, BN_OPTIONS));
} else if (isHex(value)) {
return this.soft(hexToU8a(value));
} else if (isString(value)) {
+2 -2
View File
@@ -10,7 +10,7 @@
// - Adjust formatting (just eslint differences)
// - Only English wordlist (this aligns with the wasm-crypto implementation)
// - Use util-crypto randomAsU8a (instead of randombytes)
// - Remove setting of wordlost passing of wordlist in functions
// - Remove setting of wordlist passing of wordlist in functions
// - Remove mnemonicToSeed (we only use the sync variant)
import hash from 'hash.js';
@@ -34,7 +34,7 @@ function binaryToByte (bin: string): number {
}
function bytesToBinary (bytes: number[]): string {
return bytes.map((x: number) => x.toString(2).padStart(8, '0')).join('');
return bytes.map((x) => x.toString(2).padStart(8, '0')).join('');
}
function deriveChecksumBits (entropyBuffer: Uint8Array): string {
@@ -8,7 +8,7 @@ import { mnemonicToSeedSync } from './bip39';
import { mnemonicValidate } from './validate';
/**
* @name toSeed
* @name mnemonicToLegacySeed
* @summary Creates a valid Ethereum/Bitcoin-compatible seed from a mnemonic input
* @example
* <BR>
@@ -28,13 +28,13 @@ export function mnemonicToLegacySeed (mnemonic: string, password = '', onlyJs =
assert(mnemonicValidate(mnemonic), 'Invalid bip39 mnemonic specified');
assert([32, 64].includes(byteLength), () => `Invalid seed length ${byteLength}, expected 32 or 64`);
if (byteLength && byteLength === 32) {
if (byteLength === 32) {
return isReady() && !onlyJs
? bip39ToSeed(mnemonic, password)
: mnemonicToSeedSync(mnemonic, password).subarray(0, 32);
} else if (byteLength === 64) {
return mnemonicToSeedSync(mnemonic, password);
} else {
return new Uint8Array();
}
return new Uint8Array();
}
+2 -1
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../types';
import nacl from 'tweetnacl';
@@ -22,7 +23,7 @@ import { ed25519Sign, isReady } from '@polkadot/wasm-crypto';
* naclSign([...], [...]); // => [...]
* ```
*/
export function naclSign (message: Uint8Array | string, { publicKey, secretKey }: Partial<Keypair>, onlyJs = false): Uint8Array {
export function naclSign (message: HexString | Uint8Array | string, { publicKey, secretKey }: Partial<Keypair>, onlyJs = false): Uint8Array {
assert(secretKey, 'Expected a valid secretKey');
const messageU8a = u8aToU8a(message);
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import nacl from 'tweetnacl';
import { assert, u8aToU8a } from '@polkadot/util';
@@ -20,7 +22,7 @@ import { ed25519Verify, isReady } from '@polkadot/wasm-crypto';
* naclVerify([...], [...], [...]); // => true/false
* ```
*/
export function naclVerify (message: Uint8Array | string, signature: Uint8Array | string, publicKey: Uint8Array | string, onlyJs = false): boolean {
export function naclVerify (message: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, publicKey: HexString | Uint8Array | string, onlyJs = false): boolean {
const messageU8a = u8aToU8a(message);
const publicKeyU8a = u8aToU8a(publicKey);
const signatureU8a = u8aToU8a(signature);
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/util-crypto', version: '7.3.1' };
export const packageInfo = { name: '@polkadot/util-crypto', version: '7.5.1' };
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aToU8a } from '@polkadot/util';
import { isReady, pbkdf2 } from '@polkadot/wasm-crypto';
@@ -13,7 +15,7 @@ interface Result {
salt: Uint8Array;
}
export function pbkdf2Encode (passphrase?: Buffer | Uint8Array | string, salt: Buffer | Uint8Array = randomAsU8a(), rounds = 2048, onlyJs = false): Result {
export function pbkdf2Encode (passphrase?: HexString | Buffer | Uint8Array | string, salt: Buffer | Uint8Array = randomAsU8a(), rounds = 2048, onlyJs = false): Result {
const u8aPass = u8aToU8a(passphrase);
const u8aSalt = u8aToU8a(salt);
const password = isReady() && !onlyJs
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aToHex } from '@polkadot/util';
import { randomAsU8a } from './asU8a';
@@ -19,7 +21,7 @@ import { randomAsU8a } from './asU8a';
* randomAsHex(); // => 0x...
* ```
*/
export function randomAsHex (length = 32): string {
export function randomAsHex (length = 32): HexString {
return u8aToHex(
randomAsU8a(length)
);
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { assert, u8aToU8a } from '@polkadot/util';
import { sr25519Agree } from '@polkadot/wasm-crypto';
@@ -8,7 +10,7 @@ import { sr25519Agree } from '@polkadot/wasm-crypto';
* @name schnorrkelAgreement
* @description Key agreement between other's public key and self secret key
*/
export function schnorrkelAgreement (secretKey: Uint8Array | string, publicKey: Uint8Array | string): Uint8Array {
export function schnorrkelAgreement (secretKey: HexString | Uint8Array | string, publicKey: HexString | Uint8Array | string): Uint8Array {
const secretKeyU8a = u8aToU8a(secretKey);
const publicKeyU8a = u8aToU8a(publicKey);
@@ -0,0 +1,23 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../types';
import { u8aToU8a } from '@polkadot/util';
import { sr25519DeriveKeypairHard, sr25519DeriveKeypairSoft } from '@polkadot/wasm-crypto';
import { schnorrkelKeypairFromU8a } from './keypair/fromU8a';
import { schnorrkelKeypairToU8a } from './keypair/toU8a';
export function schnorrkelDerive (keypair: Keypair, chainCode: HexString | Uint8Array | string, isHard: boolean): Keypair {
return schnorrkelKeypairFromU8a(
(isHard
? sr25519DeriveKeypairHard
: sr25519DeriveKeypairSoft
)(
schnorrkelKeypairToU8a(keypair),
u8aToU8a(chainCode)
)
);
}
@@ -1,16 +1,11 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../types';
import { u8aToU8a } from '@polkadot/util';
import { sr25519DeriveKeypairHard } from '@polkadot/wasm-crypto';
import { schnorrkelDerive } from './derive';
import { schnorrkelKeypairFromU8a } from './keypair/fromU8a';
import { schnorrkelKeypairToU8a } from './keypair/toU8a';
export function schnorrkelDeriveHard (keypair: Keypair, chainCode: Uint8Array | string): Keypair {
return schnorrkelKeypairFromU8a(
sr25519DeriveKeypairHard(schnorrkelKeypairToU8a(keypair), u8aToU8a(chainCode))
);
export function schnorrkelDeriveHard (keypair: Keypair, chainCode: HexString | Uint8Array | string): Keypair {
return schnorrkelDerive(keypair, chainCode, true);
}
@@ -1,10 +1,12 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { assert, u8aToU8a } from '@polkadot/util';
import { sr25519DerivePublicSoft } from '@polkadot/wasm-crypto';
export function schnorrkelDerivePublic (publicKey: Uint8Array | string, chainCode: Uint8Array | string): Uint8Array {
export function schnorrkelDerivePublic (publicKey: HexString | Uint8Array | string, chainCode: HexString | Uint8Array | string): Uint8Array {
const publicKeyU8a = u8aToU8a(publicKey);
assert(publicKeyU8a.length === 32, () => `Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
@@ -1,16 +1,11 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../types';
import { u8aToU8a } from '@polkadot/util';
import { sr25519DeriveKeypairSoft } from '@polkadot/wasm-crypto';
import { schnorrkelDerive } from './derive';
import { schnorrkelKeypairFromU8a } from './keypair/fromU8a';
import { schnorrkelKeypairToU8a } from './keypair/toU8a';
export function schnorrkelDeriveSoft (keypair: Keypair, chainCode: Uint8Array | string): Keypair {
return schnorrkelKeypairFromU8a(
sr25519DeriveKeypairSoft(schnorrkelKeypairToU8a(keypair), u8aToU8a(chainCode))
);
export function schnorrkelDeriveSoft (keypair: Keypair, chainCode: HexString | Uint8Array | string): Keypair {
return schnorrkelDerive(keypair, chainCode, false);
}
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../../types';
import { assert, u8aToU8a } from '@polkadot/util';
@@ -12,7 +13,7 @@ import { schnorrkelKeypairFromU8a } from './fromU8a';
* @name schnorrkelKeypairFromSeed
* @description Returns a object containing a `publicKey` & `secretKey` generated from the supplied seed.
*/
export function schnorrkelKeypairFromSeed (seed: Uint8Array | string): Keypair {
export function schnorrkelKeypairFromSeed (seed: HexString | Uint8Array | string): Keypair {
const seedU8a = u8aToU8a(seed);
assert(seedU8a.length === 32, () => `Expected a seed matching 32 bytes, found ${seedU8a.length}`);
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../../types';
import { assert, u8aToU8a } from '@polkadot/util';
@@ -9,7 +10,7 @@ const SEC_LEN = 64;
const PUB_LEN = 32;
const TOT_LEN = SEC_LEN + PUB_LEN;
export function schnorrkelKeypairFromU8a (full: Uint8Array | string): Keypair {
export function schnorrkelKeypairFromU8a (full: HexString | Uint8Array | string): Keypair {
const fullU8a = u8aToU8a(full);
assert(fullU8a.length === TOT_LEN, () => `Expected keypair with ${TOT_LEN} bytes, found ${fullU8a.length}`);
+2 -1
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../types';
import { assert, u8aToU8a } from '@polkadot/util';
@@ -10,7 +11,7 @@ import { sr25519Sign } from '@polkadot/wasm-crypto';
* @name schnorrkelSign
* @description Returns message signature of `message`, using the supplied pair
*/
export function schnorrkelSign (message: Uint8Array | string, { publicKey, secretKey }: Partial<Keypair>): Uint8Array {
export function schnorrkelSign (message: HexString | Uint8Array | string, { publicKey, secretKey }: Partial<Keypair>): Uint8Array {
assert(publicKey?.length === 32, 'Expected a valid publicKey, 32-bytes');
assert(secretKey?.length === 64, 'Expected a valid secretKey, 64-bytes');
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { assert, u8aToU8a } from '@polkadot/util';
import { sr25519Verify } from '@polkadot/wasm-crypto';
@@ -8,7 +10,7 @@ import { sr25519Verify } from '@polkadot/wasm-crypto';
* @name schnorrkelVerify
* @description Verifies the signature of `message`, using the supplied pair
*/
export function schnorrkelVerify (message: Uint8Array | string, signature: Uint8Array | string, publicKey: Uint8Array | string): boolean {
export function schnorrkelVerify (message: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, publicKey: HexString | Uint8Array | string): boolean {
const publicKeyU8a = u8aToU8a(publicKey);
const signatureU8a = u8aToU8a(signature);
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../types';
import { assert, u8aToU8a } from '@polkadot/util';
@@ -12,7 +13,7 @@ const EMPTY_U8A = new Uint8Array();
* @name schnorrkelVrfSign
* @description Sign with sr25519 vrf signing (deterministic)
*/
export function schnorrkelVrfSign (message: Uint8Array | string, { secretKey }: Partial<Keypair>, context: string | Uint8Array = EMPTY_U8A, extra: string | Uint8Array = EMPTY_U8A): Uint8Array {
export function schnorrkelVrfSign (message: HexString | Uint8Array | string, { secretKey }: Partial<Keypair>, context: HexString | string | Uint8Array = EMPTY_U8A, extra: HexString | string | Uint8Array = EMPTY_U8A): Uint8Array {
assert(secretKey?.length === 64, 'Invalid secretKey, expected 64-bytes');
return vrfSign(secretKey, u8aToU8a(context), u8aToU8a(message), u8aToU8a(extra));
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { assert, u8aToU8a } from '@polkadot/util';
import { vrfVerify } from '@polkadot/wasm-crypto';
@@ -10,7 +12,7 @@ const EMPTY_U8A = new Uint8Array();
* @name schnorrkelVrfVerify
* @description Verify with sr25519 vrf verification
*/
export function schnorrkelVrfVerify (message: Uint8Array | string, signOutput: string | Uint8Array, publicKey: Uint8Array | string, context: string | Uint8Array = EMPTY_U8A, extra: string | Uint8Array = EMPTY_U8A): boolean {
export function schnorrkelVrfVerify (message: HexString | Uint8Array | string, signOutput: HexString | string | Uint8Array, publicKey: HexString | Uint8Array | string, context: HexString | string | Uint8Array = EMPTY_U8A, extra: HexString | string | Uint8Array = EMPTY_U8A): boolean {
const publicKeyU8a = u8aToU8a(publicKey);
const proofU8a = u8aToU8a(signOutput);
+2 -1
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Params } from './types';
import scryptsy from 'scryptsy';
@@ -17,7 +18,7 @@ interface Result {
salt: Uint8Array;
}
export function scryptEncode (passphrase?: Uint8Array | string, salt = randomAsU8a(), params = DEFAULT_PARAMS): Result {
export function scryptEncode (passphrase?: HexString | Uint8Array | string, salt = randomAsU8a(), params = DEFAULT_PARAMS): Result {
const password = isReady()
? scrypt(u8aToU8a(passphrase), salt, Math.log2(params.N), params.r, params.p)
: bufferToU8a(
+2 -1
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { HashType } from './types';
import { assert, u8aEq, u8aToU8a } from '@polkadot/util';
@@ -13,7 +14,7 @@ import { secp256k1 } from './secp256k1';
* @name secp256k1Verify
* @description Verifies the signature of `message`, using the supplied pair
*/
export function secp256k1Verify (message: Uint8Array | string, signature: Uint8Array | string, address: Uint8Array | string, hashType: HashType = 'blake2'): boolean {
export function secp256k1Verify (message: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, address: HexString | Uint8Array | string, hashType: HashType = 'blake2'): boolean {
const isEthereum = hashType === 'keccak';
const u8a = u8aToU8a(signature);
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { hexToU8a, stringToU8a, u8aConcat, u8aToHex } from '@polkadot/util';
import { hexToU8a, stringToU8a, u8aConcat, u8aToHex, u8aWrapBytes } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { decodeAddress } from '../address';
@@ -9,11 +9,13 @@ import { signatureVerify } from '.';
const ADDR_ED = 'DxN4uvzwPzJLtn17yew6jEffPhXQfdKHTp2brufb98vGbPN';
const ADDR_SR = 'EK1bFgKm2FsghcttHT7TB7rNyXApFgs9fCbijMGQNyFGBQm';
const ADDR_SR_WRAP = 'J9nD3s7zssCX7bion1xctAF6xcVexcpy2uwy4jTm9JL8yuK';
const ADDR_EC = 'XyFVXiGaHxoBhXZkSh6NS2rjFyVaVNUo5UiZDqZbuSfUdji';
const ADDR_ET = '0x54Dab85EE2c7b9F7421100d7134eFb5DfA4239bF';
const MESSAGE = 'hello world';
const SIG_ED = '0x299d3bf4c8bb51af732f8067b3a3015c0862a5ff34721749d8ed6577ea2708365d1c5f76bd519009971e41156f12c70abc2533837ceb3bad9a05a99ab923de06';
const SIG_SR = '0xca01419b5a17219f7b78335658cab3b126db523a5df7be4bfc2bef76c2eb3b1dcf4ca86eb877d0a6cf6df12db5995c51d13b00e005d053b892bd09c594434288';
const SIG_SR_WRAP = '0x84b6afb1c8e54bbcb3f4872baf172580e21310e9387a53742627d6652d121447fa406b82805ed3184fb7bd519175cc9f99f283f97954d95cf966ee164df85489';
const SIG_EC = '0x994638ee586d2c5dbd9bacacbc35d9b7e9018de8f7892f00c900db63bc57b1283e2ee7bc51a9b1c1dae121ac4f4b9e2a41cd1d6bf4bb3e24d7fed6faf6d85e0501';
const SIG_ET = '0x4e35aad35793b71f08566615661c9b741d7c605bc8935ac08608dff685324d71b5704fbd14c9297d2f584ea0735f015dcf0def66b802b3f555e1db916eda4b7700';
const MUL_ED = u8aToHex(u8aConcat(new Uint8Array([0]), hexToU8a(SIG_ED)));
@@ -37,6 +39,7 @@ describe('signatureVerify', (): void => {
expect(signatureVerify(MESSAGE, SIG_ED, ADDR_ED)).toEqual({
crypto: 'ed25519',
isValid: true,
isWrapped: false,
publicKey: decodeAddress(ADDR_ED)
});
});
@@ -45,6 +48,7 @@ describe('signatureVerify', (): void => {
expect(signatureVerify(MESSAGE, SIG_EC, ADDR_EC)).toEqual({
crypto: 'ecdsa',
isValid: true,
isWrapped: false,
publicKey: decodeAddress(ADDR_EC)
});
});
@@ -53,6 +57,7 @@ describe('signatureVerify', (): void => {
expect(signatureVerify(MESSAGE, SIG_ET, ADDR_ET)).toEqual({
crypto: 'ethereum',
isValid: true,
isWrapped: false,
publicKey: hexToU8a(ADDR_ET)
});
});
@@ -67,6 +72,7 @@ describe('signatureVerify', (): void => {
)).toEqual({
crypto: 'ethereum',
isValid: true,
isWrapped: true,
publicKey: hexToU8a('0x002309df96687e44280bb72c3818358faeeb699c')
});
});
@@ -75,6 +81,7 @@ describe('signatureVerify', (): void => {
expect(signatureVerify(MESSAGE, SIG_EC, ADDR_ET)).toEqual({
crypto: 'none',
isValid: false,
isWrapped: false,
publicKey: hexToU8a(ADDR_ET)
});
});
@@ -83,14 +90,34 @@ describe('signatureVerify', (): void => {
expect(signatureVerify(MESSAGE, SIG_SR, ADDR_SR)).toEqual({
crypto: 'sr25519',
isValid: true,
isWrapped: false,
publicKey: decodeAddress(ADDR_SR)
});
});
it('verifies an sr25519 signature (with msg wrapper, without wrapped sig)', (): void => {
expect(signatureVerify(u8aWrapBytes(MESSAGE), SIG_SR_WRAP, ADDR_SR_WRAP)).toEqual({
crypto: 'sr25519',
isValid: true,
isWrapped: true,
publicKey: decodeAddress(ADDR_SR_WRAP)
});
});
it('verifies an sr25519 signature (without msg wrapper, with wrapped sig)', (): void => {
expect(signatureVerify(MESSAGE, SIG_SR_WRAP, ADDR_SR_WRAP)).toEqual({
crypto: 'sr25519',
isValid: true,
isWrapped: false,
publicKey: decodeAddress(ADDR_SR_WRAP)
});
});
it('allows various inputs', (): void => {
expect(signatureVerify(stringToU8a(MESSAGE), hexToU8a(SIG_ED), decodeAddress(ADDR_ED))).toEqual({
crypto: 'ed25519',
isValid: true,
isWrapped: false,
publicKey: decodeAddress(ADDR_ED)
});
});
@@ -99,6 +126,7 @@ describe('signatureVerify', (): void => {
expect(signatureVerify(MESSAGE, SIG_SR, ADDR_ED)).toEqual({
crypto: 'none',
isValid: false,
isWrapped: false,
publicKey: decodeAddress(ADDR_ED)
});
});
@@ -109,6 +137,7 @@ describe('signatureVerify', (): void => {
expect(signatureVerify(MESSAGE, MUL_ED, ADDR_ED)).toEqual({
crypto: 'ed25519',
isValid: true,
isWrapped: false,
publicKey: decodeAddress(ADDR_ED)
});
});
@@ -117,6 +146,7 @@ describe('signatureVerify', (): void => {
expect(signatureVerify(MESSAGE, MUL_EC, ADDR_EC)).toEqual({
crypto: 'ecdsa',
isValid: true,
isWrapped: false,
publicKey: decodeAddress(ADDR_EC)
});
});
@@ -125,6 +155,7 @@ describe('signatureVerify', (): void => {
expect(signatureVerify(MESSAGE, MUL_ET, ADDR_ET)).toEqual({
crypto: 'ethereum',
isValid: true,
isWrapped: false,
publicKey: hexToU8a(ADDR_ET)
});
});
@@ -133,6 +164,7 @@ describe('signatureVerify', (): void => {
expect(signatureVerify(MESSAGE, MUL_SR, ADDR_SR)).toEqual({
crypto: 'sr25519',
isValid: true,
isWrapped: false,
publicKey: decodeAddress(ADDR_SR)
});
});
@@ -141,6 +173,7 @@ describe('signatureVerify', (): void => {
expect(signatureVerify(MESSAGE, MUL_SR, ADDR_ED)).toEqual({
crypto: 'sr25519',
isValid: false,
isWrapped: false,
publicKey: new Uint8Array([61, 12, 55, 211, 0, 211, 97, 199, 4, 37, 17, 213, 81, 175, 166, 23, 251, 199, 144, 210, 19, 83, 186, 1, 196, 231, 14, 156, 171, 46, 141, 146])
});
});
+27 -8
View File
@@ -1,9 +1,10 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { KeypairType, VerifyResult } from '../types';
import { assert, u8aToU8a } from '@polkadot/util';
import { assert, u8aIsWrapped, u8aToU8a, u8aUnwrapBytes, u8aWrapBytes } from '@polkadot/util';
import { decodeAddress } from '../address/decode';
import { naclVerify } from '../nacl/verify';
@@ -11,13 +12,15 @@ import { schnorrkelVerify } from '../schnorrkel/verify';
import { secp256k1Verify } from '../secp256k1/verify';
interface VerifyInput {
message: Uint8Array | string;
message: Uint8Array;
publicKey: Uint8Array;
signature: Uint8Array;
}
type Verifier = [KeypairType, (message: Uint8Array | string, signature: Uint8Array, publicKey: Uint8Array) => boolean];
type VerifyFn = (result: VerifyResult, input: VerifyInput) => VerifyResult;
const secp256k1VerifyHasher = (hashType: 'blake2' | 'keccak') =>
(message: Uint8Array | string, signature: Uint8Array, publicKey: Uint8Array) =>
secp256k1Verify(message, signature, publicKey, hashType);
@@ -74,16 +77,32 @@ function verifyMultisig (result: VerifyResult, { message, publicKey, signature }
return result;
}
export function signatureVerify (message: Uint8Array | string, signature: Uint8Array | string, addressOrPublicKey: Uint8Array | string): VerifyResult {
function getVerifyFn (signature: Uint8Array): VerifyFn {
return [0, 1, 2].includes(signature[0]) && [65, 66].includes(signature.length)
? verifyMultisig
: verifyDetect;
}
export function signatureVerify (message: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, addressOrPublicKey: HexString | Uint8Array | string): VerifyResult {
const signatureU8a = u8aToU8a(signature);
assert([64, 65, 66].includes(signatureU8a.length), () => `Invalid signature length, expected [64..66] bytes, found ${signatureU8a.length}`);
const publicKey = decodeAddress(addressOrPublicKey);
const input = { message, publicKey, signature: signatureU8a };
const result: VerifyResult = { crypto: 'none', isValid: false, publicKey };
const input = { message: u8aToU8a(message), publicKey, signature: signatureU8a };
const result: VerifyResult = { crypto: 'none', isValid: false, isWrapped: u8aIsWrapped(input.message, true), publicKey };
const isWrappedBytes = u8aIsWrapped(input.message, false);
const verifyFn = getVerifyFn(signatureU8a);
return [0, 1, 2].includes(signatureU8a[0]) && [65, 66].includes(signatureU8a.length)
? verifyMultisig(result, input)
: verifyDetect(result, input);
verifyFn(result, input);
if (result.crypto !== 'none' || (result.isWrapped && !isWrappedBytes)) {
return result;
}
input.message = isWrappedBytes
? u8aUnwrapBytes(input.message)
: u8aWrapBytes(input.message);
return verifyFn(result, input);
}
+4
View File
@@ -1,6 +1,9 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './address/types';
export * from './json/types';
export interface Keypair {
publicKey: Uint8Array;
secretKey: Uint8Array;
@@ -16,5 +19,6 @@ export type KeypairType = 'ed25519' | 'sr25519' | 'ecdsa' | 'ethereum';
export interface VerifyResult {
crypto: 'none' | KeypairType;
isValid: boolean;
isWrapped: boolean;
publicKey: Uint8Array;
}
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aToHex } from '@polkadot/util';
import { xxhashAsU8a } from './asU8a';
@@ -19,7 +21,7 @@ import { xxhashAsU8a } from './asU8a';
* xxhashAsHex('abc'); // => 0x44bc2cf5ad770999
* ```
*/
export function xxhashAsHex (data: Buffer | Uint8Array | string, bitLength = 64): string {
export function xxhashAsHex (data: HexString | Buffer | Uint8Array | string, bitLength = 64): HexString {
return u8aToHex(
xxhashAsU8a(data, bitLength)
);
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aToU8a } from '@polkadot/util';
import { isReady, twox } from '@polkadot/wasm-crypto';
@@ -20,7 +22,7 @@ import xxhash64AsBn from './xxhash64/asBn';
* xxhashAsU8a('abc'); // => 0x44bc2cf5ad770999
* ```
*/
export function xxhashAsU8a (data: Buffer | Uint8Array | string, bitLength = 64, onlyJs = false): Uint8Array {
export function xxhashAsU8a (data: HexString | Buffer | Uint8Array | string, bitLength = 64, onlyJs = false): Uint8Array {
const iterations = Math.ceil(bitLength / 64);
if (isReady() && !onlyJs) {
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/util",
"version": "7.3.1",
"version": "7.5.1",
"type": "module",
"description": "A collection of useful utilities for @polkadot",
"main": "index.js",
@@ -19,9 +19,9 @@
"bugs": "https://github.com/polkadot-js/common/issues",
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util#readme",
"dependencies": {
"@babel/runtime": "^7.15.3",
"@polkadot/x-textdecoder": "7.3.1",
"@polkadot/x-textencoder": "7.3.1",
"@babel/runtime": "^7.15.4",
"@polkadot/x-textdecoder": "7.5.1",
"@polkadot/x-textencoder": "7.5.1",
"@types/bn.js": "^4.11.6",
"bn.js": "^4.12.0",
"camelcase": "^6.2.0",
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ToBn } from '../types';
import type { HexString, ToBn } from '../types';
import { hexToBn } from '../hex/toBn';
import { isBigInt } from '../is/bigInt';
@@ -25,7 +25,7 @@ import { BN } from './bn';
* bnToBn(new BN(0x1234)); // => BN(0x1234)
* ```
*/
export function bnToBn <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | string | number | null): BN {
export function bnToBn <ExtToBn extends ToBn> (value?: HexString | ExtToBn | BN | bigint | string | number | null): BN {
if (!value) {
return new BN(0);
} else if (isHex(value)) {
+4 -4
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ToBn, ToBnOptions } from '../types';
import type { HexString, ToBn, ToBnOptions } from '../types';
import type { BN } from './bn';
import { isNumber } from '../is/number';
@@ -29,9 +29,9 @@ interface Options extends ToBnOptions {
* bnToHex(new BN(0x123456)); // => '0x123456'
* ```
*/
function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, options?: Options): string;
function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, bitLength?: number, isLe?: boolean): string;
function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, arg1: number | Options = { bitLength: -1, isLe: false, isNegative: false }, arg2?: boolean): string {
function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, options?: Options): HexString;
function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, bitLength?: number, isLe?: boolean): HexString;
function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, arg1: number | Options = { bitLength: -1, isLe: false, isNegative: false }, arg2?: boolean): HexString {
if (!value) {
return ZERO_STR;
}
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { U8aLike } from '../types';
import { BN, BN_FOUR } from '../bn';
import { u8aToBn, u8aToU8a } from '../u8a';
@@ -18,7 +20,7 @@ import { u8aToBn, u8aToU8a } from '../u8a';
* console.log('value offset=', offset, 'length=', length); // 4, 0xffff
* ```
*/
export function compactFromU8a (_input: Buffer | Uint8Array | string | number[]): [number, BN] {
export function compactFromU8a (_input: U8aLike): [number, BN] {
const input = u8aToU8a(_input);
const flag = input[0] & 0b11;
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '../types';
import { hexHasPrefix } from './hasPrefix';
/**
@@ -17,7 +19,7 @@ import { hexHasPrefix } from './hasPrefix';
* console.log('With prefix', hexAddPrefix('0a0b12')); // => 0x0a0b12
* ```
*/
export function hexAddPrefix (value?: string | null): string {
export function hexAddPrefix (value?: string | null): HexString {
if (value && hexHasPrefix(value)) {
return value;
}
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '../types';
import { hexAddPrefix } from './addPrefix';
import { hexStripPrefix } from './stripPrefix';
@@ -20,7 +22,7 @@ import { hexStripPrefix } from './stripPrefix';
* console.log('fixed', hexFixLength('0x0012', 8)); // => 0x12
* ```
*/
export function hexFixLength (value: string, bitLength = -1, withPadding = false): string {
export function hexFixLength (value: string, bitLength = -1, withPadding = false): HexString {
const strLength = Math.ceil(bitLength / 4);
const hexLength = strLength + 2;
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '../types';
import { isHex } from '../is/hex';
/**
@@ -17,6 +19,6 @@ import { isHex } from '../is/hex';
* console.log('has prefix', hexHasPrefix('0x1234')); // => true
* ```
*/
export function hexHasPrefix (value?: string | null): boolean {
export function hexHasPrefix (value?: string | null): value is HexString {
return !!(value && isHex(value, -1, true) && value.substr(0, 2) === '0x');
}
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '../types';
import { assert } from '../assert';
import { isHex } from '../is/hex';
import { hexStripPrefix } from './stripPrefix';
@@ -20,7 +22,7 @@ import { hexStripPrefix } from './stripPrefix';
* hexToU8a('0x80001f', 32); // Uint8Array([0x00, 0x80, 0x00, 0x1f])
* ```
*/
export function hexToU8a (_value?: string | null, bitLength = -1): Uint8Array {
export function hexToU8a (_value?: HexString | string | null, bitLength = -1): Uint8Array {
if (!_value) {
return new Uint8Array();
}
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { U8aLike } from '../types';
import { u8aToU8a } from '../u8a/toU8a';
import { isString } from './string';
@@ -12,7 +14,7 @@ const FORMAT = [9, 10, 13];
* @description
* Checks to see if the input string or Uint8Array is printable ASCII, 32-127 + formatters
*/
export function isAscii (value?: number[] | Buffer | Uint8Array | string | null): boolean {
export function isAscii (value?: U8aLike | null): boolean {
return value
? !u8aToU8a(value).some((byte) => (byte >= 127) || (byte < 32 && !FORMAT.includes(byte)))
: isString(value);
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '../types';
const HEX_REGEX = /^0x[a-fA-F0-9]+$/;
/**
@@ -18,7 +20,7 @@ const HEX_REGEX = /^0x[a-fA-F0-9]+$/;
* isHex('0x1234', 8); // => false
* ```
*/
export function isHex (value: unknown, bitLength = -1, ignoreLength = false): value is string {
export function isHex (value: unknown, bitLength = -1, ignoreLength = false): value is HexString {
return (typeof value === 'string' && (value === '0x' || HEX_REGEX.test(value)))
? bitLength === -1
? ((value.length % 2 === 0) || ignoreLength)
+3 -1
View File
@@ -3,6 +3,8 @@
// Adapted from https://github.com/JulienPalard/is_utf8/blob/master/is_utf8.c
import type { HexString } from '../types';
import { u8aToU8a } from '../u8a/toU8a';
import { isString } from './string';
@@ -12,7 +14,7 @@ import { isString } from './string';
* @description
* Checks to see if the input string or Uint8Array is valid Utf8
*/
export function isUtf8 (value?: number[] | Buffer | Uint8Array | string | null): boolean {
export function isUtf8 (value?: HexString | number[] | Buffer | Uint8Array | string | null): boolean {
if (!value) {
return isString(value);
}
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '../types';
import { hexFixLength } from '../hex/fixLength';
import { isNull } from '../is/null';
import { isUndefined } from '../is/undefined';
@@ -20,7 +22,7 @@ import { isUndefined } from '../is/undefined';
* numberToHex(0x1234, 32); // => 0x00001234
* ```
*/
export function numberToHex (value?: number | null, bitLength = -1): string {
export function numberToHex (value?: number | null, bitLength = -1): HexString {
if (isUndefined(value) || isNull(value) || isNaN(value)) {
return '0x';
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/util', version: '7.3.1' };
export const packageInfo = { name: '@polkadot/util', version: '7.5.1' };
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '../types';
import { u8aToHex } from '../u8a/toHex';
import { stringToU8a } from './toU8a';
@@ -19,7 +21,7 @@ import { stringToU8a } from './toU8a';
* ```
*/
// eslint-disable-next-line @typescript-eslint/ban-types
export function stringToHex (value?: String | string): string {
export function stringToHex (value?: String | string): HexString {
return u8aToHex(
stringToU8a(value)
);
+7
View File
@@ -51,3 +51,10 @@ export interface Time {
export type Memoized<F> = F & {
unmemoize: (...args: unknown[]) => void;
}
export type HexDigit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f';
// One day when template strings support regex, we can improve this
export type HexString = `0x${string}`;
export type U8aLike = HexString | number[] | Buffer | Uint8Array | string;
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '../types';
import { u8aToU8a } from './toU8a';
function compare (a: Uint8Array, b: Uint8Array): number {
@@ -46,6 +48,6 @@ function compare (a: Uint8Array, b: Uint8Array): number {
* u8aCmp(new Uint8Array([0x69, 0x65]), new Uint8Array([0x68, 0x65])); // +1
* ```
*/
export function u8aCmp (a: Uint8Array | string, b: Uint8Array | string): number {
export function u8aCmp (a: HexString | Uint8Array | string, b: HexString | Uint8Array | string): number {
return compare(u8aToU8a(a), u8aToU8a(b));
}
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { U8aLike } from '../types';
import { u8aToU8a } from './toU8a';
/**
@@ -20,7 +22,7 @@ import { u8aToU8a } from './toU8a';
* ); // [1, 2, 3, 4, 5, 6]
* ```
*/
export function u8aConcat (...list: (Buffer | Uint8Array | number[] | string)[]): Uint8Array {
export function u8aConcat (...list: U8aLike[]): Uint8Array {
let length = 0;
let offset = 0;
const u8as = new Array<Uint8Array>(list.length);
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '../types';
import { u8aCmp } from './cmp';
import { u8aToU8a } from './toU8a';
@@ -22,6 +24,6 @@ function equals (a: Uint8Array, b: Uint8Array): boolean {
* u8aEq(new Uint8Array([0x68, 0x65]), new Uint8Array([0x68, 0x65])); // true
* ```
*/
export function u8aEq (a: Uint8Array | string, b: Uint8Array | string): boolean {
export function u8aEq (a: HexString | Uint8Array | string, b: HexString | Uint8Array | string): boolean {
return equals(u8aToU8a(a), u8aToU8a(b));
}
+1 -5
View File
@@ -28,11 +28,7 @@ export function u8aFixLength (value: Uint8Array, bitLength = -1, atStart = false
const result = new Uint8Array(byteLength);
if (atStart) {
result.set(value, 0);
} else {
result.set(value, byteLength - value.length);
}
result.set(value, atStart ? 0 : (byteLength - value.length));
return result;
}
+1
View File
@@ -16,3 +16,4 @@ export { u8aToBuffer } from './toBuffer';
export { u8aToHex } from './toHex';
export { u8aToString } from './toString';
export { u8aToU8a } from './toU8a';
export { U8A_WRAP_ETHEREUM, U8A_WRAP_POSTFIX, U8A_WRAP_PREFIX, u8aIsWrapped, u8aWrapBytes, u8aUnwrapBytes } from './wrap';
+22 -19
View File
@@ -1,13 +1,17 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexDigit, HexString } from '../types';
import { arrayRange } from '../array';
const ALPHABET = arrayRange(256).map((n) => n.toString(16).padStart(2, '0'));
type HexByte = `${HexDigit}${HexDigit}`;
const ALPHABET = arrayRange(256).map((n) => n.toString(16).padStart(2, '0') as HexByte);
/** @internal */
function extract (value: Uint8Array): string {
const result = new Array<string>(value.length);
const result = new Array<HexByte>(value.length);
for (let i = 0; i < value.length; i++) {
result[i] = ALPHABET[value[i]];
@@ -16,9 +20,18 @@ function extract (value: Uint8Array): string {
return result.join('');
}
/** @internal */
function unprefixed (value: Uint8Array, bitLength = -1): string {
const byteLength = Math.ceil(bitLength / 8);
return (byteLength > 0 && value.length > byteLength)
? trim(value, Math.ceil(byteLength / 2))
: extract(value);
}
/** @internal */
function trim (value: Uint8Array, halfLength: number): string {
return `${u8aToHex(value.subarray(0, halfLength), -1, false)}…${u8aToHex(value.subarray(value.length - halfLength), -1, false)}`;
return `${unprefixed(value.subarray(0, halfLength))}…${unprefixed(value.subarray(value.length - halfLength))}`;
}
/**
@@ -35,20 +48,10 @@ function trim (value: Uint8Array, halfLength: number): string {
* u8aToHex(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0xf])); // 0x68656c0f
* ```
*/
export function u8aToHex (value?: Uint8Array | null, bitLength = -1, isPrefixed = true): string {
const prefix = isPrefixed
? '0x'
: '';
if (!value?.length) {
return prefix;
}
const byteLength = Math.ceil(bitLength / 8);
return prefix + (
(byteLength > 0 && value.length > byteLength)
? trim(value, Math.ceil(byteLength / 2))
: extract(value)
);
export function u8aToHex (value?: Uint8Array | null, bitLength = -1, isPrefixed = true): HexString {
return `${isPrefixed ? '0x' : ''}${
!value || !value.length
? ''
: unprefixed(value, bitLength)
}` as HexString;
}
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { U8aLike } from '../types';
import { assert } from '../assert';
import { hexToU8a } from '../hex/toU8a';
import { isBuffer } from '../is/buffer';
@@ -24,7 +26,7 @@ import { stringToU8a } from '../string/toU8a';
* u8aToU8a(0x1234); // => Uint8Array([0x12, 0x34])
* ```
*/
export function u8aToU8a (value?: number[] | Buffer | Uint8Array | string | null): Uint8Array {
export function u8aToU8a (value?: U8aLike | null): Uint8Array {
if (!value) {
return new Uint8Array();
} else if (isHex(value)) {

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