Compare commits

..
70 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
Github Actions f0b984f141 [CI Skip] release/stable 7.3.1
skip-checks: true
2021-08-28 06:17:10 +00:00
Jaco 56e518fc92 7.3.1 (#1098) 2021-08-28 08:08:14 +02:00
Tore19 87a1ca96e3 Add stafi genesis hash (#1096) 2021-08-28 07:55:10 +02:00
Github Actions 8ef9e206d6 [CI Skip] release/beta 7.2.2-8
skip-checks: true
2021-08-26 09:30:40 +00:00
Jaco 1cdda7ca06 Bump deps (#1097) 2021-08-26 11:22:25 +02:00
Github Actions fa930e9f09 [CI Skip] release/beta 7.2.2-7
skip-checks: true
2021-08-26 06:54:37 +00:00
Jaco f6cc776e87 schnorrkelAgreement (#1095)
* schnorrkelAgreement

* Hex on sr25519 functions

* cleanups
2021-08-26 08:47:25 +02:00
Github Actions 3c4bfeb3e8 [CI Skip] release/beta 7.2.2-6
skip-checks: true
2021-08-26 06:03:11 +00:00
Jaco 6e49aaf1db Bump wasm (w/ sr agreement) (#1094) 2021-08-26 07:54:29 +02:00
Github Actions 852c4c0398 [CI Skip] release/beta 7.2.2-5
skip-checks: true
2021-08-25 08:03:48 +00:00
Jaco 9b03461c7e Align prefixes with upstream (#1093) 2021-08-25 09:55:16 +02:00
Github Actions 4d11a90188 [CI Skip] release/beta 7.2.2-4
skip-checks: true
2021-08-24 07:19:28 +00:00
Jaco b7666e9de9 Bump deps (#1091) 2021-08-24 09:11:33 +02:00
Github Actions 0129752206 [CI Skip] release/beta 7.2.2-3
skip-checks: true
2021-08-24 06:37:29 +00:00
pan 11fa66441d add bifrost genesis hash (#1090) 2021-08-24 08:28:40 +02:00
Eliott Teissonniere 9ed08def61 add nodle ledger specs (#1089) 2021-08-24 08:28:01 +02:00
Github Actions f1ccfad087 [CI Skip] release/beta 7.2.2-2
skip-checks: true
2021-08-21 08:33:43 +00:00
Jaco 4f9198f1f3 Bumps (#1088)
* Bumps

* Upgrade @polkadot/ts
2021-08-21 10:25:08 +02:00
Github Actions 6bd6c8340f [CI Skip] release/beta 7.2.2-1
skip-checks: true
2021-08-17 07:44:23 +00:00
Jaco 4355df9e9b Bump deps (#1087) 2021-08-17 09:35:40 +02:00
Github Actions 272fe62031 [CI Skip] release/beta 7.2.2-0
skip-checks: true
2021-08-16 06:07:50 +00:00
Jaco 5ab88bcd35 Bump deps (#1086) 2021-08-16 07:58:42 +02:00
Github Actions 4a5659a579 [CI Skip] release/stable 7.2.1
skip-checks: true
2021-08-15 08:46:10 +00:00
Jaco c4a8aa2dd7 7.2.1 (#1085)
* 7.2.1

* Update CHANGELOG.md

* u8aEmpty
2021-08-15 10:38:48 +02:00
Github Actions 2ad042e44d [CI Skip] release/beta 7.1.3-4
skip-checks: true
2021-08-13 11:56:50 +00:00
Jaco Greeff 4615fcfbde bump berry 2021-08-13 14:48:47 +03:00
Github Actions f90d84500d [CI Skip] release/beta 7.1.3-3
skip-checks: true
2021-08-13 11:02:19 +00:00
Jaco e919446341 Bump dev (#1084)
* Bump dev

* Cleanup circular dep

* CHANGELOG

* typo
2021-08-13 12:54:03 +02:00
Github Actions 8f942dcabe [CI Skip] release/beta 7.1.3-2
skip-checks: true
2021-08-12 08:09:40 +00:00
Nantian 2e4de2093c fix bigint type (#1079) 2021-08-12 10:00:58 +02:00
Github Actions 0202a1f1d4 [CI Skip] release/beta 7.1.3-1
skip-checks: true
2021-08-12 05:24:15 +00:00
Jaco Greeff 1e256fedaa pre 2021-08-12 08:16:52 +03:00
135 changed files with 2843 additions and 3055 deletions
File diff suppressed because one or more lines are too long
+631
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -10,4 +10,4 @@ plugins:
- path: .yarn/plugins/@yarnpkg/plugin-version.cjs
spec: "@yarnpkg/plugin-version"
yarnPath: .yarn/releases/yarn-3.0.0-rc.2.cjs
yarnPath: .yarn/releases/yarn-3.0.1.cjs
+53
View File
@@ -1,5 +1,58 @@
# 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:
- Added Bifrost genesisHash (Thanks to https://github.com/awesomepan)
- Added Stafi genesisHash (Thanks to https://github.com/Tore19)
- Add Ledger support for Nodle (Thanks to https://github.com/ETeissonniere)
Changes:
- 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
## 7.2.1 Aug 15, 2021
Contributed:
- Always use `bigint` type to indicate instance (Thanks to https://github.com/ntduan)
Changes:
- Added `u8aEmpty` helper check, all 0 or no length
- Cleanup additional circular dependencies detected by rollup
## 7.1.2 Aug 11, 2021
Changes:
+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)']
}
});
+7 -6
View File
@@ -7,7 +7,7 @@
"packages/*"
],
"resolutions": {
"typescript": "^4.3.5"
"typescript": "^4.4.4"
},
"scripts": {
"build": "polkadot-dev-build-ts",
@@ -23,11 +23,12 @@
"test:one": "polkadot-dev-run-test --runInBand"
},
"devDependencies": {
"@babel/core": "^7.15.0",
"@polkadot/dev": "^0.62.58",
"@polkadot/ts": "^0.4.4",
"@babel/core": "^7.15.8",
"@polkadot/dev": "^0.62.71",
"@polkadot/ts": "^0.4.9",
"@types/ed2curve": "^0.2.2",
"@types/jest": "^26.0.24"
"@types/jest": "^27.0.2"
},
"version": "7.1.2"
"version": "7.5.1",
"packageManager": "yarn@3.0.1"
}
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/hw-ledger-transports",
"version": "7.1.2",
"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.14.8",
"@ledgerhq/hw-transport": "^6.3.0",
"@ledgerhq/hw-transport-webhid": "^6.3.0",
"@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.1.2' };
export const packageInfo = { name: '@polkadot/hw-ledger-transports', version: '7.5.1' };
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/hw-ledger",
"version": "7.1.2",
"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.14.8",
"@polkadot/hw-ledger-transports": "7.1.2",
"@polkadot/util": "7.1.2",
"@zondax/ledger-substrate": "^0.17.3"
"@babel/runtime": "^7.15.4",
"@polkadot/hw-ledger-transports": "7.5.1",
"@polkadot/util": "7.5.1",
"@zondax/ledger-substrate": "^0.18.0"
}
}
+2 -1
View File
@@ -4,7 +4,7 @@
import type Transport from '@ledgerhq/hw-transport';
import type { SubstrateApp } from '@zondax/ledger-substrate';
import { newCentrifugeApp, newDockApp, newEdgewareApp, newEquilibriumApp, newKusamaApp, newPolkadotApp, newPolymeshApp, newStatemineApp } from '@zondax/ledger-substrate';
import { newCentrifugeApp, newDockApp, newEdgewareApp, newEquilibriumApp, newKusamaApp, newNodleApp, newPolkadotApp, newPolymeshApp, newStatemineApp } from '@zondax/ledger-substrate';
// These match up with the keys of the knownLedger object in the @polkadot/networks/defaults.ts
export const ledgerApps: Record<string, (transport: Transport) => SubstrateApp> = {
@@ -13,6 +13,7 @@ export const ledgerApps: Record<string, (transport: Transport) => SubstrateApp>
edgeware: newEdgewareApp,
equilibrium: newEquilibriumApp,
kusama: newKusamaApp,
'nodle-chain': newNodleApp,
polkadot: newPolkadotApp,
polymesh: newPolymeshApp,
statemine: newStatemineApp
+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.1.2' };
export const packageInfo = { name: '@polkadot/hw-ledger', version: '7.5.1' };
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/keyring",
"version": "7.1.2",
"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.14.8",
"@polkadot/util": "7.1.2",
"@polkadot/util-crypto": "7.1.2"
"@babel/runtime": "^7.15.4",
"@polkadot/util": "7.5.1",
"@polkadot/util-crypto": "7.5.1"
},
"peerDependencies": {
"@polkadot/util": "7.1.2",
"@polkadot/util-crypto": "7.1.2"
"@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.1.2' };
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';
+15 -15
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,11 +170,11 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
encodePkcs8: (passphrase?: string): Uint8Array => {
return recode(passphrase);
},
encryptMessage: (message: string | Uint8Array, recipientPublicKey: string | Uint8Array, _nonce?: 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');
const { nonce, sealed } = naclSeal(u8aToU8a(message), convertSecretKeyToCurve25519(secretKey), convertPublicKeyToCurve25519(u8aToU8a(recipientPublicKey)), _nonce);
const { nonce, sealed } = naclSeal(u8aToU8a(message), convertSecretKeyToCurve25519(secretKey), convertPublicKeyToCurve25519(u8aToU8a(recipientPublicKey)), nonceIn);
return u8aConcat(nonce, sealed);
},
@@ -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 => {
return signatureVerify(message, signature, TYPE_ADDRESS[type](u8aToU8a(_signerPublic))).isValid;
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,14 +223,12 @@ 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 => {
const signerPublic = TYPE_ADDRESS[type](u8aToU8a(_signerPublic));
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);
}
const result = signatureVerify(message, u8aConcat(TYPE_PREFIX[type], vrfResult.subarray(32)), signerPublic);
const result = signatureVerify(message, u8aConcat(TYPE_PREFIX[type], vrfResult.subarray(32)), TYPE_ADDRESS[type](u8aToU8a(signerPublic)));
return result.isValid && u8aEq(vrfResult.subarray(0, 32), vrfHash(vrfResult.subarray(32), 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);
+8 -10
View File
@@ -6,13 +6,13 @@ import type { KeyringInstance, KeyringOptions } from './types';
import { hexToU8a } from '@polkadot/util';
import { KeypairType } from '@polkadot/util-crypto/types';
import { Keyring } from './keyring';
import { createPair } from './pair';
import Keyring from '.';
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.1.2",
"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.14.8"
"@babel/runtime": "^7.15.4"
},
"devDependencies": {
"@polkadot/util": "7.1.2",
"@polkadot/x-fetch": "7.1.2"
"@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])
)
: []
];
})
+10
View File
@@ -8,6 +8,9 @@ import type { KnownGenesis, KnownIcon, KnownLedger, KnownTestnet } from './types
// last. This make lookups for the current a simple genesisHash[0]
// (See Kusama as an example)
export const knownGenesis: KnownGenesis = {
bifrost: [
'0x9f28c6a68e0fc9646eff64935684f6eeeece527e37bbe1f213d22caa1d9d6bed'
],
centrifuge: [
'0x67dddf2673b69e5f875f6f25277495834398eafd67f492e09f3f3345e003d1b5'
],
@@ -37,6 +40,9 @@ export const knownGenesis: KnownGenesis = {
'0xe3777fa922cafbff200cadeaea1a76bd7898ad5b89f7848999058b50e715f636', // Kusama CC2
'0x3fd7b9eb6a00376e5be61f01abb429ffb0b104be05eaff4d458da48fcd425baf' // Kusama CC1
],
'nodle-chain': [
'0xa3d114c2b8d0627c1aa9b134eafcf7d05ca561fdc19fb388bb9457f81809fb23'
],
plasm: [
'0x3e86364d4b4894021cb2a0390bcf2feb5517d5292f2de2bb9404227e908b0b8b'
],
@@ -46,6 +52,9 @@ export const knownGenesis: KnownGenesis = {
polymesh: [
'0x9deeb940c92ae02111c3bd5baca89970384f4c9849f02a1b2e53e66414d30f9f'
],
stafi: [
'0x290a4149f09ea0e402c74c1c7e96ae4239588577fe78932f94f5404c68243d80'
],
statemine: [
'0x48239ef607d7928874027a43a67689209727dfb3d3dc5e5b03a39bdc2eda771a'
],
@@ -73,6 +82,7 @@ export const knownLedger: KnownLedger = {
edgeware: 0x0000020b,
equilibrium: 0x05f5e0fd,
kusama: 0x000001b2,
'nodle-chain': 0x000003eb,
polkadot: 0x00000162,
polymesh: 0x00000253,
statemine: 0x000001b2 // common-good on Kusama, shares derivation
+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.1.2' };
export const packageInfo = { name: '@polkadot/networks', version: '7.5.1' };
+69 -6
View File
@@ -129,13 +129,13 @@ export const knownSubstrate: KnownSubstrate[] = [
website: 'https://polymath.network/'
},
{
decimals: null,
displayName: 'SubstraTEE',
network: 'substratee',
decimals: [12],
displayName: 'Integritee',
network: 'integritee',
prefix: 13,
standardAccount: '*25519',
symbols: null,
website: 'https://www.substratee.com'
symbols: ['TEER'],
website: 'https://integritee.network'
},
{
decimals: [0],
@@ -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',
@@ -551,6 +578,24 @@ export const knownSubstrate: KnownSubstrate[] = [
symbols: ['HKO'],
website: 'https://parallel.fi/'
},
{
decimals: null,
displayName: 'Integritee Incognito',
network: 'integritee-incognito',
prefix: 113,
standardAccount: '*25519',
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',
@@ -596,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',
@@ -604,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'
}
];
+8 -8
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/util-crypto",
"version": "7.1.2",
"version": "7.5.1",
"type": "module",
"description": "A collection of useful crypto utilities for @polkadot",
"main": "index.js",
@@ -21,15 +21,15 @@
"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.14.8",
"@polkadot/networks": "7.1.2",
"@polkadot/util": "7.1.2",
"@polkadot/wasm-crypto": "^4.1.2",
"@polkadot/x-randomvalues": "7.1.2",
"@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.5.1",
"base-x": "^3.0.8",
"base64-js": "^1.5.1",
"blakejs": "^1.1.1",
"bn.js": "^4.11.9",
"bn.js": "^4.12.0",
"create-hash": "^1.2.0",
"ed2curve": "^0.3.0",
"elliptic": "^6.5.4",
@@ -47,6 +47,6 @@
"@types/xxhashjs": "^0.2.2"
},
"peerDependencies": {
"@polkadot/util": "7.1.2"
"@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.1.2' };
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)
);
@@ -0,0 +1,32 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Keypair } from '../types';
import { u8aToHex } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { schnorrkelAgreement, schnorrkelKeypairFromSeed } from '.';
describe('agreement', (): void => {
let pairA: Keypair;
let pairB: Keypair;
beforeEach(async (): Promise<void> => {
await waitReady();
pairA = schnorrkelKeypairFromSeed('0x98b3d305d5a5eace562387e47e59badd4d77e3f72cabfb10a60f8a197059f0a8');
pairB = schnorrkelKeypairFromSeed('0x9732eea001851ff862d949a1699c9971f3a26edbede2ad7922cbbe9a0701f366');
});
it('matches a known agreement (both ways)', (): void => {
const TEST = '0xb03a0b198c34c16f35cae933d88b16341b4cef3e84e851f20e664c6a30527f4e';
expect(
u8aToHex(schnorrkelAgreement(pairA.secretKey, pairB.publicKey))
).toEqual(TEST);
expect(
u8aToHex(schnorrkelAgreement(pairB.secretKey, pairA.publicKey))
).toEqual(TEST);
});
});
@@ -0,0 +1,21 @@
// 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';
/**
* @name schnorrkelAgreement
* @description Key agreement between other's public key and self secret key
*/
export function schnorrkelAgreement (secretKey: HexString | Uint8Array | string, publicKey: HexString | Uint8Array | string): Uint8Array {
const secretKeyU8a = u8aToU8a(secretKey);
const publicKeyU8a = u8aToU8a(publicKey);
assert(publicKeyU8a.length === 32, () => `Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
assert(secretKeyU8a.length === 64, () => `Invalid secretKey, received ${secretKeyU8a.length} bytes, expected 64`);
return sr25519Agree(publicKeyU8a, secretKeyU8a);
}
@@ -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,15 +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 { 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): Keypair {
return schnorrkelKeypairFromU8a(
sr25519DeriveKeypairHard(schnorrkelKeypairToU8a(keypair), chainCode)
);
export function schnorrkelDeriveHard (keypair: Keypair, chainCode: HexString | Uint8Array | string): Keypair {
return schnorrkelDerive(keypair, chainCode, true);
}
@@ -1,8 +1,15 @@
// 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, chainCode: Uint8Array): Uint8Array {
return sr25519DerivePublicSoft(publicKey, chainCode);
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`);
return sr25519DerivePublicSoft(publicKeyU8a, u8aToU8a(chainCode));
}
@@ -1,15 +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 { 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): Keypair {
return schnorrkelKeypairFromU8a(
sr25519DeriveKeypairSoft(schnorrkelKeypairToU8a(keypair), 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
export { schnorrkelAgreement } from './agreement';
export { schnorrkelDeriveHard } from './deriveHard';
export { schnorrkelDerivePublic } from './derivePublic';
export { schnorrkelDeriveSoft } from './deriveSoft';
@@ -1,8 +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 { Keypair } from '../../types';
import { assert, u8aToU8a } from '@polkadot/util';
import { sr25519KeypairFromSeed } from '@polkadot/wasm-crypto';
import { schnorrkelKeypairFromU8a } from './fromU8a';
@@ -11,8 +13,12 @@ import { schnorrkelKeypairFromU8a } from './fromU8a';
* @name schnorrkelKeypairFromSeed
* @description Returns a object containing a `publicKey` & `secretKey` generated from the supplied seed.
*/
export function schnorrkelKeypairFromSeed (seed: Uint8Array): 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}`);
return schnorrkelKeypairFromU8a(
sr25519KeypairFromSeed(seed)
sr25519KeypairFromSeed(seedU8a)
);
}
@@ -1,14 +1,22 @@
// 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';
const SEC_LEN = 64;
const PUB_LEN = 32;
const TOT_LEN = SEC_LEN + PUB_LEN;
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}`);
export function schnorrkelKeypairFromU8a (full: Uint8Array): Keypair {
return {
publicKey: full.slice(SEC_LEN, SEC_LEN + PUB_LEN),
secretKey: full.slice(0, SEC_LEN)
publicKey: fullU8a.slice(SEC_LEN, TOT_LEN),
secretKey: fullU8a.slice(0, SEC_LEN)
};
}
+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) {
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/util",
"version": "7.1.2",
"version": "7.5.1",
"type": "module",
"description": "A collection of useful utilities for @polkadot",
"main": "index.js",
@@ -19,12 +19,12 @@
"bugs": "https://github.com/polkadot-js/common/issues",
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util#readme",
"dependencies": {
"@babel/runtime": "^7.14.8",
"@polkadot/x-textdecoder": "7.1.2",
"@polkadot/x-textencoder": "7.1.2",
"@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.11.9",
"camelcase": "^5.3.1",
"bn.js": "^4.12.0",
"camelcase": "^6.2.0",
"ip-regex": "^4.3.0"
}
}
+1 -1
View File
@@ -3,7 +3,7 @@
import { BN, bnSqrt } from '.';
const TESTS: [string | number | BN | BigInt, string | number][] = [
const TESTS: [string | number | BN | bigint, string | number][] = [
[0, 0],
[1, 1],
[4, 2],
+1 -1
View File
@@ -23,7 +23,7 @@ const SQRT_MAX_SAFE_INTEGER = new BN(94906265);
* bnSqrt(new BN(16)).toString(); // => '4'
* ```
*/
export function bnSqrt <ExtToBn extends ToBn> (value: ExtToBn | BN | BigInt | string | number | null): BN {
export function bnSqrt <ExtToBn extends ToBn> (value: ExtToBn | BN | bigint | string | number | null): BN {
const n = bnToBn(value);
assert(n.gte(BN_ZERO), 'square root of negative numbers is not supported');
+3 -3
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';
@@ -11,7 +11,7 @@ import { BN } from './bn';
/**
* @name bnToBn
* @summary Creates a BN value from a BN, BigInt, string (base 10 or hex) or number input.
* @summary Creates a BN value from a BN, bigint, string (base 10 or hex) or number input.
* @description
* `null` inputs returns a `0x0` result, BN values returns the value, numbers returns a BN representation.
* @example
@@ -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 -3
View File
@@ -40,9 +40,9 @@ function createValue (valueBn: BN, byteLength: number, { isLe, isNegative }: Opt
* bnToU8a(new BN(0x1234)); // => [0x12, 0x34]
* ```
*/
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null, options?: Options): Uint8Array;
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null, bitLength?: number, isLe?: boolean): Uint8Array;
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null, arg1: number | Options = { bitLength: -1, isLe: true, isNegative: false }, arg2?: boolean): Uint8Array {
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, options?: Options): Uint8Array;
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, bitLength?: number, isLe?: boolean): Uint8Array;
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, arg1: number | Options = { bitLength: -1, isLe: true, isNegative: false }, arg2?: boolean): Uint8Array {
const options: Options = {
bitLength: -1,
isLe: true,
+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;
+1 -1
View File
@@ -21,7 +21,7 @@ const MAX_U32 = new BN(2).pow(new BN(32 - 2)).subn(1);
* console.log(compactToU8a(511, 32)); // Uint8Array([0b11111101, 0b00000111])
* ```
*/
export function compactToU8a (_value: BN | BigInt | number): Uint8Array {
export function compactToU8a (_value: BN | bigint | number): Uint8Array {
const value = bnToBn(_value);
if (value.lte(MAX_U8)) {
+2 -2
View File
@@ -29,7 +29,7 @@ interface Options {
}
interface BalanceFormatter {
<ExtToBn extends ToBn> (input?: number | string | BN | BigInt | ExtToBn, options?: Options, decimals?: number): string;
<ExtToBn extends ToBn> (input?: number | string | BN | bigint | ExtToBn, options?: Options, decimals?: number): string;
calcSi (text: string, decimals?: number): SiDef;
findSi (type: string): SiDef;
getDefaults (): Defaults;
@@ -44,7 +44,7 @@ let defaultDecimals = DEFAULT_DECIMALS;
let defaultUnit = DEFAULT_UNIT;
// Formats a string/number with <prefix>.<postfix><type> notation
function _formatBalance <ExtToBn extends ToBn> (input?: number | string | BN | BigInt | ExtToBn, options: Options | boolean = true, optDecimals: number = defaultDecimals): string {
function _formatBalance <ExtToBn extends ToBn> (input?: number | string | BN | bigint | ExtToBn, options: Options | boolean = true, optDecimals: number = defaultDecimals): string {
let text = bnToBn(input).toString();
if (text.length === 0 || text === '0') {
+1 -1
View File
@@ -18,7 +18,7 @@ function formatValue (elapsed: number): string {
return `${elapsed / 3600 | 0}h`;
}
export function formatElapsed <ExtToBn extends ToBn> (now?: Date | null, value?: BigInt | BN | ExtToBn | Date | number | null): string {
export function formatElapsed <ExtToBn extends ToBn> (now?: Date | null, value?: bigint | BN | ExtToBn | Date | number | null): string {
const tsNow = (now && now.getTime()) || 0;
const tsValue = value instanceof Date
? value.getTime()
+1 -1
View File
@@ -7,6 +7,6 @@ import type { ToBn } from '../types';
import { bnToBn } from '../bn/toBn';
import { formatDecimal } from './formatDecimal';
export function formatNumber <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null): string {
export function formatNumber <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null): string {
return formatDecimal(bnToBn(value).toString());
}
+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();
}

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