Compare commits

..
78 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
Github Actions 56a3d19083 [CI Skip] release/stable 7.1.2
skip-checks: true
2021-08-11 15:21:50 +00:00
Jaco caf76a7511 Ensure packageInfo from networks doesn't clobber crypto (#1076)
* Ensure packageInfo from networks doesn't clobber crypto

* 7.1.2

* Update CHANGELOG.md

* Extract network sorting

* ... revert, CC still not happy, maybe another day...
2021-08-11 17:14:28 +02:00
Github Actions 834a1e6a52 [CI Skip] release/beta 7.1.2-0
skip-checks: true
2021-08-10 09:23:32 +00:00
Jaco 7a5b1207b0 Minor x-bundle style cleanups (#1074) 2021-08-10 11:15:10 +02:00
Github Actions 8221576d25 [CI Skip] release/stable 7.1.1
skip-checks: true
2021-08-02 08:41:20 +00:00
Jaco 1f9d36d4db 7.1.1 (#1073) 2021-08-02 10:32:37 +02:00
Github Actions b292f2ae1d [CI Skip] release/beta 7.0.4-0
skip-checks: true
2021-08-02 04:26:52 +00:00
Song ZhouandJaco 7eddfc25c9 Add in ability to encrypt/decrypt msg with keyring (#1070)
* feat: able to encrypt & decrypt message in keyring - ed25519 & sr25519 types

* chore: make eslint happy

* test: add in one more test on cross-usage of ed25519 & sr25519

* make lint happy without eslint-disable

* assert away secp256k1 for encrypt/decrypt

* Update packages/keyring/src/pair/index.ts

* Update packages/keyring/src/pair/index.ts

Co-authored-by: Jaco <jacogr@gmail.com>
2021-08-02 06:18:58 +02:00
144 changed files with 3128 additions and 3158 deletions
+2 -1
View File
@@ -16,4 +16,5 @@
6.0.5
7.0.2
7.0.3
7.0.3
7.1.2
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
+72
View File
@@ -1,5 +1,77 @@
# 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:
- Ensure `@polkadot/util-crypto` doesn't re-export `packageInfo` from `@polkadot/networks`
- Minor TS style cleanups in `@polkadot/x-bundle`
## 7.1.1 Aug 2, 2021
Contributed:
- Add keyring encrypt/decrypt functionality (Thanks to https://github.com/RoyTimes)
Changes:
- Bump Ledger libraries to latest versions
## 7.0.3 Jul 26, 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)']
}
});
+8 -6
View File
@@ -7,7 +7,7 @@
"packages/*"
],
"resolutions": {
"typescript": "^4.3.5"
"typescript": "^4.4.4"
},
"scripts": {
"build": "polkadot-dev-build-ts",
@@ -23,10 +23,12 @@
"test:one": "polkadot-dev-run-test --runInBand"
},
"devDependencies": {
"@babel/core": "^7.14.8",
"@polkadot/dev": "^0.62.57",
"@polkadot/ts": "^0.4.4",
"@types/jest": "^26.0.24"
"@babel/core": "^7.15.8",
"@polkadot/dev": "^0.62.71",
"@polkadot/ts": "^0.4.9",
"@types/ed2curve": "^0.2.2",
"@types/jest": "^27.0.2"
},
"version": "7.0.3"
"version": "7.5.1",
"packageManager": "yarn@3.0.1"
}
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/hw-ledger-transports",
"version": "7.0.3",
"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.2.0",
"@ledgerhq/hw-transport-webhid": "^6.2.0",
"@ledgerhq/hw-transport-webusb": "^6.2.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.2.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.0.3' };
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.0.3",
"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.0.3",
"@polkadot/util": "^7.0.3",
"@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.0.3' };
export const packageInfo = { name: '@polkadot/hw-ledger', version: '7.5.1' };
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/keyring",
"version": "7.0.3",
"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.0.3",
"@polkadot/util-crypto": "7.0.3"
"@babel/runtime": "^7.15.4",
"@polkadot/util": "7.5.1",
"@polkadot/util-crypto": "7.5.1"
},
"peerDependencies": {
"@polkadot/util": "7.0.3",
"@polkadot/util-crypto": "7.0.3"
"@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.0.3' };
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';
+109 -1
View File
@@ -18,6 +18,10 @@ describe('pair', (): void => {
});
const SIGNATURE = new Uint8Array([80, 191, 198, 147, 225, 207, 75, 88, 126, 39, 129, 109, 191, 38, 72, 181, 75, 254, 81, 143, 244, 79, 237, 38, 236, 141, 28, 252, 134, 26, 169, 234, 79, 33, 153, 158, 151, 34, 175, 188, 235, 20, 35, 135, 83, 120, 139, 211, 233, 130, 1, 208, 201, 215, 73, 80, 56, 98, 185, 196, 11, 8, 193, 14]);
const ENCRYPTED = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 132, 59, 53, 85, 227, 40, 107, 48, 234, 198, 238, 157, 238, 224, 235, 179, 75, 153, 241, 142, 254]);
// the last byte is changed from 254 -> 253
const ENCRYPTED_CHANGED = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 132, 59, 53, 85, 227, 40, 107, 48, 234, 198, 238, 157, 238, 224, 235, 179, 75, 153, 241, 142, 253]);
it('has a publicKey', (): void => {
expect(
@@ -53,7 +57,7 @@ describe('pair', (): void => {
it('fails a correctly signed message (signer changed)', (): void => {
expect(
keyring.alice.verify(
new Uint8Array([0x61, 0x62, 0x63, 0x64, 0x65]),
new Uint8Array([0x61, 0x62, 0x63, 0x64]),
SIGNATURE,
keyring.bob.publicKey
)
@@ -94,6 +98,93 @@ describe('pair', (): void => {
).toBe(false);
});
it('allows encrypting', (): void => {
const message = new Uint8Array([0x61, 0x62, 0x63, 0x64, 0x65]);
expect(
keyring.alice.encryptMessage(
message,
keyring.bob.publicKey,
new Uint8Array(24)
)
).toEqual(ENCRYPTED);
});
it('validates a correctly encrypted message', (): void => {
const message = new Uint8Array([0x61, 0x62, 0x63, 0x64, 0x65]);
expect(
keyring.bob.decryptMessage(
ENCRYPTED,
keyring.alice.publicKey
)
).toEqual(message);
});
it('fails a correctly encrypted message (message changed)', (): void => {
expect(
keyring.bob.decryptMessage(
ENCRYPTED_CHANGED,
keyring.alice.publicKey
)
).toEqual(null);
});
it('fails a correctly encrypted message (sender changed)', (): void => {
expect(
keyring.bob.decryptMessage(
ENCRYPTED,
keyring.charlie.publicKey
)
).toEqual(null);
});
it('fails a correctly encrypted message (receiver changed)', (): void => {
expect(
keyring.charlie.decryptMessage(
ENCRYPTED,
keyring.alice.publicKey
)
).toEqual(null);
});
it('validates encryption between ed25519 & sr25519 key pairs', (): void => {
const PASS = 'testing';
const encodedA = keyring.alice.encodePkcs8(PASS);
const encodedB = keyring.bob.encodePkcs8(PASS);
const pairA = createPair({ toSS58, type: 'sr25519' }, { publicKey: keyring.alice.publicKey });
const pairB = createPair({ toSS58, type: 'sr25519' }, { publicKey: keyring.bob.publicKey });
pairA.decodePkcs8(PASS, encodedA);
pairB.decodePkcs8(PASS, encodedB);
const message = new Uint8Array([0x61, 0x62, 0x63, 0x64, 0x65]);
// alice-sr25519 -> bob-ed25519
const encrypted1 = pairA.encryptMessage(message, keyring.bob.publicKey);
// alice-sr25519 -> bob-sr25519
const encrypted2 = pairA.encryptMessage(message, pairB.publicKey);
// alice-ed25519 -> bob-sr25519
const encrypted3 = keyring.alice.encryptMessage(message, pairB.publicKey);
// decrypt: Bob-ed25519 - use alice-ed25519 pubkey
expect(
keyring.bob.decryptMessage(encrypted3, keyring.alice.publicKey)
).toEqual(message);
// decrypt: Bob-ed25519 - use alice-sr25519 pubkey
expect(
keyring.bob.decryptMessage(encrypted1, pairA.publicKey)
).toEqual(message);
// decrypt: Bob-sr25519 - use alice-sr25519 pubkey
expect(
pairB.decryptMessage(encrypted2, pairA.publicKey)
).toEqual(message);
});
it('allows setting/getting of meta', (): void => {
keyring.bob.setMeta({ foo: 'bar', something: 'else' });
@@ -183,5 +274,22 @@ describe('pair', (): void => {
});
expect(json.address).toEqual(u8aToHex(PUBLICDERIVED));
});
it('denies access to encryptMessage/decryptMessage API', (): void => {
const PASS = 'testing';
const encoded = keyring.alice.encodePkcs8(PASS);
const pair = createPair({ toSS58, type: 'ethereum' }, { publicKey: keyring.alice.publicKey });
pair.decodePkcs8(PASS, encoded);
expect(
() => pair.encryptMessage(
new Uint8Array(4), // null message
keyring.bob.publicKey,
new Uint8Array(24)
)
).toThrow('Secp256k1 not supported yet');
});
});
});
+30 -11
View File
@@ -1,13 +1,13 @@
// 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';
import { assert, u8aConcat, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util';
import { blake2AsU8a, ethereumEncode, keccakAsU8a, keyExtractPath, keyFromPath, naclKeypairFromSeed as naclFromSeed, naclSign, schnorrkelKeypairFromSeed as schnorrkelFromSeed, schnorrkelSign, schnorrkelVrfSign, schnorrkelVrfVerify, secp256k1Compress, secp256k1Expand, secp256k1KeypairFromSeed as secp256k1FromSeed, secp256k1Sign, signatureVerify } from '@polkadot/util-crypto';
import { blake2AsU8a, convertPublicKeyToCurve25519, convertSecretKeyToCurve25519, ethereumEncode, keccakAsU8a, keyExtractPath, keyFromPath, naclKeypairFromSeed as naclFromSeed, naclOpen, naclSeal, naclSign, schnorrkelKeypairFromSeed as schnorrkelFromSeed, schnorrkelSign, schnorrkelVrfSign, schnorrkelVrfVerify, secp256k1Compress, secp256k1Expand, secp256k1KeypairFromSeed as secp256k1FromSeed, secp256k1Sign, signatureVerify } from '@polkadot/util-crypto';
import { decodePair } from './decode';
import { encodePair } from './encode';
@@ -145,6 +145,19 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
},
// eslint-disable-next-line sort-keys
decodePkcs8,
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(
messageU8a.slice(24, messageU8a.length),
messageU8a.slice(0, 24),
convertPublicKeyToCurve25519(u8aToU8a(senderPublicKey)),
convertSecretKeyToCurve25519(secretKey)
);
},
derive: (suri: string, meta?: KeyringPair$Meta): KeyringPair => {
assert(type !== 'ethereum', 'Unable to derive on this keypair');
assert(!isLocked(secretKey), 'Cannot derive on a locked keypair');
@@ -157,13 +170,21 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
encodePkcs8: (passphrase?: string): Uint8Array => {
return recode(passphrase);
},
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)), nonceIn);
return u8aConcat(nonce, sealed);
},
lock: (): void => {
secretKey = new Uint8Array();
},
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(
@@ -188,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') {
@@ -202,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 -42
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,48 +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
derive: (suri: string, meta?: KeyringPair$Meta): KeyringPair =>
pair,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
encodePkcs8: (passphrase?: string): Uint8Array =>
new Uint8Array(0),
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 -8
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,12 +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;
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.0.3",
"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.0.3",
"@polkadot/x-fetch": "7.0.3"
"@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 -42
View File
@@ -1,46 +1,5 @@
// Copyright 2017-2021 @polkadot/networks authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Network, SubstrateNetwork } from './types';
import { knownGenesis, knownIcon, knownLedger, knownTestnet } from './defaults';
import { knownSubstrate } from './substrate';
export * from './interfaces';
export { packageInfo } from './packageInfo';
// These are known prefixes that are not sorted
const UNSORTED = [0, 2, 42];
export const allNetworks = knownSubstrate.map((o): SubstrateNetwork => {
const network = o.network || '';
const n = o as SubstrateNetwork;
n.slip44 = knownLedger[network];
n.hasLedgerSupport = !!n.slip44;
n.genesisHash = knownGenesis[network] || [];
n.icon = knownIcon[network] || 'substrate';
n.isIgnored = !network || !!knownTestnet[network] || network.startsWith('reserved');
return n;
});
// The list of available/claimed prefixes
// - no testnets
// - we only include those where we have a standardAccount
// - when no icon has been specified, default to substrate
// - sort by name, however we keep 0, 2, 42 first in the list
export const availableNetworks = allNetworks
.filter((n): n is Network => !n.isIgnored && !!n.network)
.sort((a, b) =>
UNSORTED.includes(a.prefix) === UNSORTED.includes(b.prefix)
? 0
: UNSORTED.includes(a.prefix)
? -1
: UNSORTED.includes(b.prefix)
? 1
: a.displayName.localeCompare(b.displayName)
);
// A filtered list of those chains we have details about (genesisHashes)
export const selectableNetworks = availableNetworks.filter((n) => n.genesisHash.length || n.prefix === 42);
+43
View File
@@ -0,0 +1,43 @@
// Copyright 2017-2021 @polkadot/networks authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Network, SubstrateNetwork } from './types';
import { knownGenesis, knownIcon, knownLedger, knownTestnet } from './defaults';
import { knownSubstrate } from './substrate';
// These are known prefixes that are not sorted
const UNSORTED = [0, 2, 42];
export const allNetworks = knownSubstrate.map((o): SubstrateNetwork => {
const network = o.network || '';
const n = o as SubstrateNetwork;
n.slip44 = knownLedger[network];
n.hasLedgerSupport = !!n.slip44;
n.genesisHash = knownGenesis[network] || [];
n.icon = knownIcon[network] || 'substrate';
n.isIgnored = !network || !!knownTestnet[network] || !o.standardAccount;
return n;
});
// The list of available/claimed prefixes
// - no testnets
// - we only include those where we have a standardAccount
// - sort by name, however we keep 0, 2, 42 first in the list
export const availableNetworks = allNetworks
.filter((n): n is Network => !n.isIgnored && !!n.network)
.sort((a, b) =>
UNSORTED.includes(a.prefix) === UNSORTED.includes(b.prefix)
? 0
: UNSORTED.includes(a.prefix)
? -1
: UNSORTED.includes(b.prefix)
? 1
: a.displayName.localeCompare(b.displayName)
);
// A filtered list of those chains we have details about (genesisHashes)
export const selectableNetworks = availableNetworks.filter((n) => n.genesisHash.length || n.prefix === 42);
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/networks', version: '7.0.3' };
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'
}
];
+9 -8
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/util-crypto",
"version": "7.0.3",
"version": "7.5.1",
"type": "module",
"description": "A collection of useful crypto utilities for @polkadot",
"main": "index.js",
@@ -21,16 +21,17 @@
"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.0.3",
"@polkadot/util": "7.0.3",
"@polkadot/wasm-crypto": "^4.1.2",
"@polkadot/x-randomvalues": "7.0.3",
"@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",
"hash.js": "^1.1.7",
"js-sha3": "^0.8.0",
@@ -46,6 +47,6 @@
"@types/xxhashjs": "^0.2.2"
},
"peerDependencies": {
"@polkadot/util": "7.0.3"
"@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();
}
@@ -0,0 +1,12 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import ed2curve from 'ed2curve';
export function convertSecretKeyToCurve25519 (secretKey: Uint8Array): Uint8Array {
return ed2curve.convertSecretKey(secretKey);
}
export function convertPublicKeyToCurve25519 (publicKey: Uint8Array): Uint8Array {
return ed2curve.convertPublicKey(publicKey) as Uint8Array;
}
+1
View File
@@ -15,3 +15,4 @@ export { naclVerify } from './verify';
export { naclBoxKeypairFromSecret } from './box/fromSecret';
export { naclOpen } from './open';
export { naclSeal } from './seal';
export { convertSecretKeyToCurve25519, convertPublicKeyToCurve25519 } from './convertKey';
+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
@@ -1,4 +1,4 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from '@polkadot/networks';
export * from '@polkadot/networks/interfaces';
+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.0.3' };
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.0.3",
"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.0.3",
"@polkadot/x-textencoder": "7.0.3",
"@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') {

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