Compare commits

..
82 Commits
Author SHA1 Message Date
Github Actions 11ab3a4f6b [CI Skip] release/stable 7.6.1
skip-checks: true
2021-10-23 10:54:38 +00:00
Jaco 0ba57b26d1 7.6.1 (#1140)
* 7.6.1

* Adjust GlobalThis

* Adjust
2021-10-23 13:47:23 +03:00
Github Actions 36c2389985 [CI Skip] release/beta 7.5.2-4
skip-checks: true
2021-10-23 10:20:12 +00:00
Jaco 93d5041e8f Adjust base* validation function (#1139)
* Adjust base* validation function

* Adjust sr25519 derive functions

* More dedupe

* Rename

* Adjust
2021-10-23 13:11:58 +03:00
Github Actions f4d933936e [CI Skip] release/beta 7.5.2-3
skip-checks: true
2021-10-23 09:42:50 +00:00
Jaco 2cdaf71c4b Sync with paritytech/ss58-registry (#1138)
* Sync with paritytech/ss58-registry

* Since registry location

* Adjust defaults with json location

* Adjust

* Adjust comments

* prefix 42
2021-10-23 12:34:53 +03:00
Github Actions 6982380aff [CI Skip] release/beta 7.5.2-2
skip-checks: true
2021-10-23 09:00:25 +00:00
Jaco 2cc2c4d415 isAscii adjustments (#1137)
* isAscii adjustments

* Adjust negation
2021-10-23 11:52:41 +03:00
Github Actions da38e0f890 [CI Skip] release/beta 7.5.2-1
skip-checks: true
2021-10-23 08:39:18 +00:00
Jaco c7c1723914 User ArrayBuffer internally to xxhash (#1133) 2021-10-23 11:30:23 +03:00
Github Actions 15e85bf4b9 [CI Skip] release/beta 7.5.2-0
skip-checks: true
2021-10-17 09:39:09 +00:00
Jaco e7771b02a4 Bump dev (#1132)
* Bump dev

* eslint 8 fixes

* Bump
2021-10-17 12:32:45 +03:00
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
148 changed files with 3222 additions and 3433 deletions
+1
View File
@@ -13,6 +13,7 @@ jobs:
CI_LOG: 123
run: |
yarn install --immutable | grep -v 'YN0013'
yarn build
yarn networks:crosscheck
- name: issue
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
+65
View File
@@ -1,5 +1,70 @@
# CHANGELOG
## 7.6.1 Oct 23, 2021
Changes:
- Update `xxhash*` to only use `Uint8Array` internally, no `Buffer`
- Adjust `isAscii` to check against original string codepoints (when provided)
- Adjust networks to sync with `paritytech/ss58-registry`
- Dedupe internal sr25519/ed25519 derivation functions
- Bump Ledger libraries to latest versions
## 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
- Cleanup rollup build where `x-global` yields undefined
## 7.3.1 Aug 28, 2021
Contributed:
- Added Bifrost genesisHash (Thanks to https://github.com/awesomepan)
- Added Stafi genesisHash (Thanks to https://github.com/Tore19)
- Add Ledger support for Nodle (Thanks to https://github.com/ETeissonniere)
Changes:
- Add support for `schnorrkelAgreement` (as exposed by new `wasm-crypto`)
- Ensure `schnorrkel*` functions allows hex inputs
- `@polkadot/wasm-crypto` 4.2.1
- Sync with upstream Substrate ss58 registry
## 7.2.1 Aug 15, 2021
Contributed:
- Always use `bigint` type to indicate instance (Thanks to https://github.com/ntduan)
Changes:
- Added `u8aEmpty` helper check, all 0 or no length
- Cleanup additional circular dependencies detected by rollup
## 7.1.2 Aug 11, 2021
Changes:
+1 -17
View File
@@ -16,21 +16,5 @@ module.exports = Object.assign({}, config, {
'@polkadot/x-(fetch|randomvalues|textdecoder|textencoder|ws)(.*)$': '<rootDir>/packages/x-$1/src/node',
'@polkadot/x-global(.*)$': '<rootDir>/packages/x-global/src/$1',
'@polkadot/x-rxjs(.*)$': '<rootDir>/packages/x-rxjs/src/$1'
},
modulePathIgnorePatterns: [
'<rootDir>/packages/hw-ledger/build',
'<rootDir>/packages/hw-ledger-transports/build',
'<rootDir>/packages/keyring/build',
'<rootDir>/packages/networks/build',
'<rootDir>/packages/util/build',
'<rootDir>/packages/util-crypto/build',
'<rootDir>/packages/x-fetch/build',
'<rootDir>/packages/x-global/build',
'<rootDir>/packages/x-randomvalues/build',
'<rootDir>/packages/x-rxjs/build',
'<rootDir>/packages/x-textdecoder/build',
'<rootDir>/packages/x-textencoder/build',
'<rootDir>/packages/x-ws/build'
],
transformIgnorePatterns: ['/node_modules/(?!@polkadot)']
}
});
+7 -6
View File
@@ -7,7 +7,7 @@
"packages/*"
],
"resolutions": {
"typescript": "^4.3.5"
"typescript": "^4.4.4"
},
"scripts": {
"build": "polkadot-dev-build-ts",
@@ -23,11 +23,12 @@
"test:one": "polkadot-dev-run-test --runInBand"
},
"devDependencies": {
"@babel/core": "^7.15.0",
"@polkadot/dev": "^0.62.58",
"@polkadot/ts": "^0.4.4",
"@babel/core": "^7.15.8",
"@polkadot/dev": "^0.63.6",
"@polkadot/ts": "^0.4.10",
"@types/ed2curve": "^0.2.2",
"@types/jest": "^26.0.24"
"@types/jest": "^27.0.2"
},
"version": "7.1.2"
"version": "7.6.1",
"packageManager": "yarn@3.0.1"
}
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/hw-ledger-transports",
"version": "7.1.2",
"version": "7.6.1",
"type": "module",
"repository": "github:polkadot-js/common",
"author": "Jaco Greeff <jacogr@gmail.com>",
@@ -15,12 +15,12 @@
"node": ">=14.0.0"
},
"dependencies": {
"@babel/runtime": "^7.14.8",
"@ledgerhq/hw-transport": "^6.3.0",
"@ledgerhq/hw-transport-webhid": "^6.3.0",
"@ledgerhq/hw-transport-webusb": "^6.3.0"
"@babel/runtime": "^7.15.4",
"@ledgerhq/hw-transport": "^6.11.0",
"@ledgerhq/hw-transport-webhid": "^6.11.0",
"@ledgerhq/hw-transport-webusb": "^6.11.0"
},
"optionalDependencies": {
"@ledgerhq/hw-transport-node-hid-singleton": "^6.3.0"
"@ledgerhq/hw-transport-node-hid-singleton": "^6.11.0"
}
}
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/hw-ledger-transports', version: '7.1.2' };
export const packageInfo = { name: '@polkadot/hw-ledger-transports', version: '7.6.1' };
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/hw-ledger",
"version": "7.1.2",
"version": "7.6.1",
"type": "module",
"repository": "github:polkadot-js/common",
"author": "Jaco Greeff <jacogr@gmail.com>",
@@ -16,9 +16,9 @@
"node": ">=14.0.0"
},
"dependencies": {
"@babel/runtime": "^7.14.8",
"@polkadot/hw-ledger-transports": "7.1.2",
"@polkadot/util": "7.1.2",
"@zondax/ledger-substrate": "^0.17.3"
"@babel/runtime": "^7.15.4",
"@polkadot/hw-ledger-transports": "7.6.1",
"@polkadot/util": "7.6.1",
"@zondax/ledger-substrate": "^0.18.0"
}
}
+2 -1
View File
@@ -4,7 +4,7 @@
import type Transport from '@ledgerhq/hw-transport';
import type { SubstrateApp } from '@zondax/ledger-substrate';
import { newCentrifugeApp, newDockApp, newEdgewareApp, newEquilibriumApp, newKusamaApp, newPolkadotApp, newPolymeshApp, newStatemineApp } from '@zondax/ledger-substrate';
import { newCentrifugeApp, newDockApp, newEdgewareApp, newEquilibriumApp, newKusamaApp, newNodleApp, newPolkadotApp, newPolymeshApp, newStatemineApp } from '@zondax/ledger-substrate';
// These match up with the keys of the knownLedger object in the @polkadot/networks/defaults.ts
export const ledgerApps: Record<string, (transport: Transport) => SubstrateApp> = {
@@ -13,6 +13,7 @@ export const ledgerApps: Record<string, (transport: Transport) => SubstrateApp>
edgeware: newEdgewareApp,
equilibrium: newEquilibriumApp,
kusama: newKusamaApp,
'nodle-chain': newNodleApp,
polkadot: newPolkadotApp,
polymesh: newPolymeshApp,
statemine: newStatemineApp
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/hw-ledger', version: '7.1.2' };
export const packageInfo = { name: '@polkadot/hw-ledger', version: '7.6.1' };
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/keyring",
"version": "7.1.2",
"version": "7.6.1",
"type": "module",
"description": "Keyring management",
"author": "Jaco Greeff <jacogr@gmail.com>",
@@ -19,12 +19,12 @@
"bugs": "https://github.com/polkadot-js/common/issues",
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/keyring#readme",
"dependencies": {
"@babel/runtime": "^7.14.8",
"@polkadot/util": "7.1.2",
"@polkadot/util-crypto": "7.1.2"
"@babel/runtime": "^7.15.4",
"@polkadot/util": "7.6.1",
"@polkadot/util-crypto": "7.6.1"
},
"peerDependencies": {
"@polkadot/util": "7.1.2",
"@polkadot/util-crypto": "7.1.2"
"@polkadot/util": "7.6.1",
"@polkadot/util-crypto": "7.6.1"
}
}
+24 -12
View File
@@ -74,7 +74,7 @@ describe('keypair', (): void => {
it('allows adding from JSON', (): void => {
expect(
keyring.addFromJson(
JSON.parse('{"address":"5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua","encoded":"0xb4a14995d25ab609f3686e9fa45f1fb237cd833f33f00d4b12c51858ca070d96972e47d73aae5eeb0fc06f923826cf0943fdb02c2c2ee30ef52a7912663053940d1da4da66b3a3f520ae07422c1c94b2d95690fca9d1f4a997623bb2923a8833280e19e7f72c3c5cfa343974e60e2b3dc53b404fdaf330756daad5e4e3","encoding":{"content":"pkcs8","type":"xsalsa20-poly1305","version":"0"},"meta":{"isTesting":true,"name":"alice"}}')
JSON.parse('{"address":"5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua","encoded":"0xb4a14995d25ab609f3686e9fa45f1fb237cd833f33f00d4b12c51858ca070d96972e47d73aae5eeb0fc06f923826cf0943fdb02c2c2ee30ef52a7912663053940d1da4da66b3a3f520ae07422c1c94b2d95690fca9d1f4a997623bb2923a8833280e19e7f72c3c5cfa343974e60e2b3dc53b404fdaf330756daad5e4e3","encoding":{"content":"pkcs8","type":"xsalsa20-poly1305","version":"0"},"meta":{"isTesting":true,"name":"alice"}}') as KeyringPair$Json
).publicKey
).toEqual(
new Uint8Array([209, 114, 167, 76, 218, 76, 134, 89, 18, 195, 43, 160, 168, 10, 87, 174, 105, 171, 174, 65, 14, 92, 203, 89, 222, 232, 78, 47, 68, 50, 219, 79])
@@ -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);
@@ -160,7 +172,7 @@ describe('keypair', (): void => {
it('allows adding from JSON', (): void => {
expect(
keyring.addFromJson(
JSON.parse('{"address":"5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua","encoded":"0xb4a14995d25ab609f3686e9fa45f1fb237cd833f33f00d4b12c51858ca070d96972e47d73aae5eeb0fc06f923826cf0943fdb02c2c2ee30ef52a7912663053940d1da4da66b3a3f520ae07422c1c94b2d95690fca9d1f4a997623bb2923a8833280e19e7f72c3c5cfa343974e60e2b3dc53b404fdaf330756daad5e4e3","encoding":{"content":"pkcs8","type":"xsalsa20-poly1305","version":"0"},"meta":{"isTesting":true,"name":"alice"}}')
JSON.parse('{"address":"5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua","encoded":"0xb4a14995d25ab609f3686e9fa45f1fb237cd833f33f00d4b12c51858ca070d96972e47d73aae5eeb0fc06f923826cf0943fdb02c2c2ee30ef52a7912663053940d1da4da66b3a3f520ae07422c1c94b2d95690fca9d1f4a997623bb2923a8833280e19e7f72c3c5cfa343974e60e2b3dc53b404fdaf330756daad5e4e3","encoding":{"content":"pkcs8","type":"xsalsa20-poly1305","version":"0"},"meta":{"isTesting":true,"name":"alice"}}') as KeyringPair$Json
).publicKey
).toEqual(
new Uint8Array([209, 114, 167, 76, 218, 76, 134, 89, 18, 195, 43, 160, 168, 10, 87, 174, 105, 171, 174, 65, 14, 92, 203, 89, 222, 232, 78, 47, 68, 50, 219, 79])
@@ -239,7 +251,7 @@ describe('keypair', (): void => {
it('allows adding from JSON', (): void => {
expect(
keyring.addFromJson(
JSON.parse('{"address":"5DzMsaYFhmpRdErWrP6K6PD7UXzYoeETToSBUrZSvxasqWRz","encoded":"0xa192d39b42bc1601bf61df31039a554228593fadf870bc837b658a5114627aca199fff596260c95fe8994c66a47636cf0270aa08f402ba5541038753960d00e6c3af5e239ec58fb1eef3db7d6bc266f4853bdfe4ed17122d9092d879014d53980d2ee57f6f55a88c38836447d8645008e8815379626addc8f81f80cd49a2","encoding":{"content":"pkcs8","type":"xsalsa20-poly1305","version":"2"},"meta":{}}')
JSON.parse('{"address":"5DzMsaYFhmpRdErWrP6K6PD7UXzYoeETToSBUrZSvxasqWRz","encoded":"0xa192d39b42bc1601bf61df31039a554228593fadf870bc837b658a5114627aca199fff596260c95fe8994c66a47636cf0270aa08f402ba5541038753960d00e6c3af5e239ec58fb1eef3db7d6bc266f4853bdfe4ed17122d9092d879014d53980d2ee57f6f55a88c38836447d8645008e8815379626addc8f81f80cd49a2","encoding":{"content":"pkcs8","type":"xsalsa20-poly1305","version":"2"},"meta":{}}') as KeyringPair$Json
).address
).toEqual('5DzMsaYFhmpRdErWrP6K6PD7UXzYoeETToSBUrZSvxasqWRz');
});
@@ -247,7 +259,7 @@ describe('keypair', (): void => {
it('allows creation from JSON', (): void => {
keyring.setSS58Format(2);
const pair = keyring.createFromJson(
JSON.parse('{"address":"0x02fde629668eb2bcc7d748f40a7e597f7c7b363498ff3db31f03ce4854937883ad","encoded":"qIhAhKqtf2iyEoWEr8nmBdksSI8EHHCpgJHToqd6Pl8AgAAAAQAAAAgAAADDZ//fj/BRRj+0+bl1KAlYgoPJp6nEUwiw0fVqO2BW4mjEgQ+iWwJEgDf1JUtecbzOlfhTXBzqX/dIYzLgUADrF4EFEPpboCWiU1iN7W/3DM1cOTRVvTGcbdIqW//z3axhz961qzeJVUIFgllwGe/euLUPIlKbIkiN/CsRYdQ=","encoding":{"content":["pkcs8","ecdsa"],"type":["scrypt","xsalsa20-poly1305"],"version":"3"},"meta":{"genesisHash":"0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe","name":"ecdsa","tags":[],"whenCreated":1600925898271}}')
JSON.parse('{"address":"0x02fde629668eb2bcc7d748f40a7e597f7c7b363498ff3db31f03ce4854937883ad","encoded":"qIhAhKqtf2iyEoWEr8nmBdksSI8EHHCpgJHToqd6Pl8AgAAAAQAAAAgAAADDZ//fj/BRRj+0+bl1KAlYgoPJp6nEUwiw0fVqO2BW4mjEgQ+iWwJEgDf1JUtecbzOlfhTXBzqX/dIYzLgUADrF4EFEPpboCWiU1iN7W/3DM1cOTRVvTGcbdIqW//z3axhz961qzeJVUIFgllwGe/euLUPIlKbIkiN/CsRYdQ=","encoding":{"content":["pkcs8","ecdsa"],"type":["scrypt","xsalsa20-poly1305"],"version":"3"},"meta":{"genesisHash":"0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe","name":"ecdsa","tags":[],"whenCreated":1600925898271}}') as KeyringPair$Json
);
expect(pair.address).toEqual('DHL8HKFuTTR55JzzLmkJRCAfPBbuevKaT9cXikxbEV97Ko8');
@@ -256,7 +268,7 @@ describe('keypair', (): void => {
it('fails toJson() when password is incorrect', (): void => {
const pair = keyring.createFromJson(
JSON.parse('{"address":"0x02fde629668eb2bcc7d748f40a7e597f7c7b363498ff3db31f03ce4854937883ad","encoded":"qIhAhKqtf2iyEoWEr8nmBdksSI8EHHCpgJHToqd6Pl8AgAAAAQAAAAgAAADDZ//fj/BRRj+0+bl1KAlYgoPJp6nEUwiw0fVqO2BW4mjEgQ+iWwJEgDf1JUtecbzOlfhTXBzqX/dIYzLgUADrF4EFEPpboCWiU1iN7W/3DM1cOTRVvTGcbdIqW//z3axhz961qzeJVUIFgllwGe/euLUPIlKbIkiN/CsRYdQ=","encoding":{"content":["pkcs8","ecdsa"],"type":["scrypt","xsalsa20-poly1305"],"version":"3"},"meta":{"genesisHash":"0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe","name":"ecdsa","tags":[],"whenCreated":1600925898271}}')
JSON.parse('{"address":"0x02fde629668eb2bcc7d748f40a7e597f7c7b363498ff3db31f03ce4854937883ad","encoded":"qIhAhKqtf2iyEoWEr8nmBdksSI8EHHCpgJHToqd6Pl8AgAAAAQAAAAgAAADDZ//fj/BRRj+0+bl1KAlYgoPJp6nEUwiw0fVqO2BW4mjEgQ+iWwJEgDf1JUtecbzOlfhTXBzqX/dIYzLgUADrF4EFEPpboCWiU1iN7W/3DM1cOTRVvTGcbdIqW//z3axhz961qzeJVUIFgllwGe/euLUPIlKbIkiN/CsRYdQ=","encoding":{"content":["pkcs8","ecdsa"],"type":["scrypt","xsalsa20-poly1305"],"version":"3"},"meta":{"genesisHash":"0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe","name":"ecdsa","tags":[],"whenCreated":1600925898271}}') as KeyringPair$Json
);
expect(
@@ -266,7 +278,7 @@ describe('keypair', (): void => {
it('pass toJson() when password is correct', (): void => {
const pair = keyring.createFromJson(
JSON.parse('{"address":"0x02fde629668eb2bcc7d748f40a7e597f7c7b363498ff3db31f03ce4854937883ad","encoded":"qIhAhKqtf2iyEoWEr8nmBdksSI8EHHCpgJHToqd6Pl8AgAAAAQAAAAgAAADDZ//fj/BRRj+0+bl1KAlYgoPJp6nEUwiw0fVqO2BW4mjEgQ+iWwJEgDf1JUtecbzOlfhTXBzqX/dIYzLgUADrF4EFEPpboCWiU1iN7W/3DM1cOTRVvTGcbdIqW//z3axhz961qzeJVUIFgllwGe/euLUPIlKbIkiN/CsRYdQ=","encoding":{"content":["pkcs8","ecdsa"],"type":["scrypt","xsalsa20-poly1305"],"version":"3"},"meta":{"genesisHash":"0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe","name":"ecdsa","tags":[],"whenCreated":1600925898271}}')
JSON.parse('{"address":"0x02fde629668eb2bcc7d748f40a7e597f7c7b363498ff3db31f03ce4854937883ad","encoded":"qIhAhKqtf2iyEoWEr8nmBdksSI8EHHCpgJHToqd6Pl8AgAAAAQAAAAgAAADDZ//fj/BRRj+0+bl1KAlYgoPJp6nEUwiw0fVqO2BW4mjEgQ+iWwJEgDf1JUtecbzOlfhTXBzqX/dIYzLgUADrF4EFEPpboCWiU1iN7W/3DM1cOTRVvTGcbdIqW//z3axhz961qzeJVUIFgllwGe/euLUPIlKbIkiN/CsRYdQ=","encoding":{"content":["pkcs8","ecdsa"],"type":["scrypt","xsalsa20-poly1305"],"version":"3"},"meta":{"genesisHash":"0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe","name":"ecdsa","tags":[],"whenCreated":1600925898271}}') as KeyringPair$Json
);
expect(
@@ -393,7 +405,7 @@ describe('keypair', (): void => {
it('allows adding from JSON', (): void => {
const pair = keyring.addFromJson(
JSON.parse('{"address":"KWCv1L3QX9LDPwY4VzvLmarEmXjVJidUzZcinvVnmxAJJCBou","encoded":"U8qFEaghhmNV2PgFhjqzmhyUy37Ok7abfFU2MNsBd0sAgAAAAQAAAAgAAAA3+NniKogzNphiMNueB1X0sGA07B6CaXWfpXPx45iSXoTTprwzU5mOoSqUWO0GKHROI72LN+uJ8Yfv6Ll6JOOV3VPKfoVoFmYm+zDrrMPa0gk5E5kUuSijxADcE6zUrliPVr0Ix/qaghu5SJ7RtWDQLBf4Hp86SJ8Gg6gTSSk=","encoding":{"content":["pkcs8","ethereum"],"type":["scrypt","xsalsa20-poly1305"],"version":"3"},"meta":{}}')
JSON.parse('{"address":"KWCv1L3QX9LDPwY4VzvLmarEmXjVJidUzZcinvVnmxAJJCBou","encoded":"U8qFEaghhmNV2PgFhjqzmhyUy37Ok7abfFU2MNsBd0sAgAAAAQAAAAgAAAA3+NniKogzNphiMNueB1X0sGA07B6CaXWfpXPx45iSXoTTprwzU5mOoSqUWO0GKHROI72LN+uJ8Yfv6Ll6JOOV3VPKfoVoFmYm+zDrrMPa0gk5E5kUuSijxADcE6zUrliPVr0Ix/qaghu5SJ7RtWDQLBf4Hp86SJ8Gg6gTSSk=","encoding":{"content":["pkcs8","ethereum"],"type":["scrypt","xsalsa20-poly1305"],"version":"3"},"meta":{}}') as KeyringPair$Json
);
expect(pair.publicKey).toEqual(hexToU8a('0x03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077'));
@@ -410,7 +422,7 @@ describe('keypair', (): void => {
const MESSAGE = stringToU8a('just some test message');
const signer = keyring.createFromUri(PHRASE);
const verifier = keyring.addFromJson(
JSON.parse('{"address":"KWCv1L3QX9LDPwY4VzvLmarEmXjVJidUzZcinvVnmxAJJCBou","encoded":"U8qFEaghhmNV2PgFhjqzmhyUy37Ok7abfFU2MNsBd0sAgAAAAQAAAAgAAAA3+NniKogzNphiMNueB1X0sGA07B6CaXWfpXPx45iSXoTTprwzU5mOoSqUWO0GKHROI72LN+uJ8Yfv6Ll6JOOV3VPKfoVoFmYm+zDrrMPa0gk5E5kUuSijxADcE6zUrliPVr0Ix/qaghu5SJ7RtWDQLBf4Hp86SJ8Gg6gTSSk=","encoding":{"content":["pkcs8","ethereum"],"type":["scrypt","xsalsa20-poly1305"],"version":"3"},"meta":{}}')
JSON.parse('{"address":"KWCv1L3QX9LDPwY4VzvLmarEmXjVJidUzZcinvVnmxAJJCBou","encoded":"U8qFEaghhmNV2PgFhjqzmhyUy37Ok7abfFU2MNsBd0sAgAAAAQAAAAgAAAA3+NniKogzNphiMNueB1X0sGA07B6CaXWfpXPx45iSXoTTprwzU5mOoSqUWO0GKHROI72LN+uJ8Yfv6Ll6JOOV3VPKfoVoFmYm+zDrrMPa0gk5E5kUuSijxADcE6zUrliPVr0Ix/qaghu5SJ7RtWDQLBf4Hp86SJ8Gg6gTSSk=","encoding":{"content":["pkcs8","ethereum"],"type":["scrypt","xsalsa20-poly1305"],"version":"3"},"meta":{}}') as KeyringPair$Json
);
const signature = signer.sign(MESSAGE);
@@ -427,7 +439,7 @@ describe('keypair', (): void => {
const MESSAGE = stringToU8a('just some test message');
const signer = keyring.createFromUri(PHRASE);
const verifier = keyring.addFromJson(
JSON.parse('{"address":"KWCv1L3QX9LDPwY4VzvLmarEmXjVJidUzZcinvVnmxAJJCBou","encoded":"U8qFEaghhmNV2PgFhjqzmhyUy37Ok7abfFU2MNsBd0sAgAAAAQAAAAgAAAA3+NniKogzNphiMNueB1X0sGA07B6CaXWfpXPx45iSXoTTprwzU5mOoSqUWO0GKHROI72LN+uJ8Yfv6Ll6JOOV3VPKfoVoFmYm+zDrrMPa0gk5E5kUuSijxADcE6zUrliPVr0Ix/qaghu5SJ7RtWDQLBf4Hp86SJ8Gg6gTSSk=","encoding":{"content":["pkcs8","ethereum"],"type":["scrypt","xsalsa20-poly1305"],"version":"3"},"meta":{}}')
JSON.parse('{"address":"KWCv1L3QX9LDPwY4VzvLmarEmXjVJidUzZcinvVnmxAJJCBou","encoded":"U8qFEaghhmNV2PgFhjqzmhyUy37Ok7abfFU2MNsBd0sAgAAAAQAAAAgAAAA3+NniKogzNphiMNueB1X0sGA07B6CaXWfpXPx45iSXoTTprwzU5mOoSqUWO0GKHROI72LN+uJ8Yfv6Ll6JOOV3VPKfoVoFmYm+zDrrMPa0gk5E5kUuSijxADcE6zUrliPVr0Ix/qaghu5SJ7RtWDQLBf4Hp86SJ8Gg6gTSSk=","encoding":{"content":["pkcs8","ethereum"],"type":["scrypt","xsalsa20-poly1305"],"version":"3"},"meta":{}}') as KeyringPair$Json
);
const signature = signer.sign(MESSAGE, { withType: true });
@@ -496,7 +508,7 @@ describe('keypair', (): void => {
});
it('can decode from a version 2 JSON file', (): void => {
const pair = keyring.addFromJson(JSON.parse(PAIR));
const pair = keyring.addFromJson(JSON.parse(PAIR) as KeyringPair$Json);
pair.decodePkcs8(PASS2);
@@ -526,7 +538,7 @@ describe('keypair', (): void => {
});
it('can decode from a version 3 JSON file', (): void => {
const pair = keyring.addFromJson(JSON.parse(PAIR));
const pair = keyring.addFromJson(JSON.parse(PAIR) as KeyringPair$Json);
pair.decodePkcs8(PASS3);
@@ -545,7 +557,7 @@ describe('keypair', (): void => {
});
it('can decode from a version 3 JSON file', (): void => {
const pair = keyring.addFromJson(JSON.parse(PAIR));
const pair = keyring.addFromJson(JSON.parse(PAIR) as KeyringPair$Json);
pair.decodePkcs8(PASS3);
+5 -7
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));
}
}
@@ -237,7 +235,7 @@ export class Keyring implements KeyringInstance {
return this.type === 'ethereum'
? ethereumEncode(address)
: encodeAddress(address, isUndefined(ss58Format) ? this.#ss58 : ss58Format);
}
};
/**
* @name getPair
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/keyring', version: '7.1.2' };
export const packageInfo = { name: '@polkadot/keyring', version: '7.6.1' };
+1 -1
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { EncryptedJsonEncoding } from '@polkadot/util-crypto/json/types';
import type { EncryptedJsonEncoding } from '@polkadot/util-crypto/types';
import type { PairInfo } from './types';
import { assert, isUndefined, u8aEq } from '@polkadot/util';
+15 -15
View File
@@ -1,8 +1,8 @@
// Copyright 2017-2021 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { EncryptedJsonEncoding } from '@polkadot/util-crypto/json/types';
import type { Keypair, KeypairType } from '@polkadot/util-crypto/types';
import type { HexString } from '@polkadot/util/types';
import type { EncryptedJsonEncoding, Keypair, KeypairType } from '@polkadot/util-crypto/types';
import type { KeyringPair, KeyringPair$Json, KeyringPair$Meta, SignOptions } from '../types';
import type { PairInfo } from './types';
@@ -145,13 +145,15 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
},
// eslint-disable-next-line sort-keys
decodePkcs8,
decryptMessage: (encryptedMessageWithNonce: string | Uint8Array, senderPublicKey: string | Uint8Array): Uint8Array | null => {
decryptMessage: (encryptedMessageWithNonce: HexString | string | Uint8Array, senderPublicKey: HexString | string | Uint8Array): Uint8Array | null => {
assert(!isLocked(secretKey), 'Cannot encrypt with a locked key pair');
assert(!['ecdsa', 'ethereum'].includes(type), 'Secp256k1 not supported yet');
const messageU8a = u8aToU8a(encryptedMessageWithNonce);
return naclOpen(
u8aToU8a(encryptedMessageWithNonce.slice(24, encryptedMessageWithNonce.length)),
u8aToU8a(encryptedMessageWithNonce.slice(0, 24)),
messageU8a.slice(24, messageU8a.length),
messageU8a.slice(0, 24),
convertPublicKeyToCurve25519(u8aToU8a(senderPublicKey)),
convertSecretKeyToCurve25519(secretKey)
);
@@ -168,11 +170,11 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
encodePkcs8: (passphrase?: string): Uint8Array => {
return recode(passphrase);
},
encryptMessage: (message: string | Uint8Array, recipientPublicKey: string | Uint8Array, _nonce?: Uint8Array): Uint8Array => {
encryptMessage: (message: HexString | string | Uint8Array, recipientPublicKey: HexString | string | Uint8Array, nonceIn?: Uint8Array): Uint8Array => {
assert(!isLocked(secretKey), 'Cannot encrypt with a locked key pair');
assert(!['ecdsa', 'ethereum'].includes(type), 'Secp256k1 not supported yet');
const { nonce, sealed } = naclSeal(u8aToU8a(message), convertSecretKeyToCurve25519(secretKey), convertPublicKeyToCurve25519(u8aToU8a(recipientPublicKey)), _nonce);
const { nonce, sealed } = naclSeal(u8aToU8a(message), convertSecretKeyToCurve25519(secretKey), convertPublicKeyToCurve25519(u8aToU8a(recipientPublicKey)), nonceIn);
return u8aConcat(nonce, sealed);
},
@@ -182,7 +184,7 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
setMeta: (additional: KeyringPair$Meta): void => {
meta = { ...meta, ...additional };
},
sign: (message: string | Uint8Array, options: SignOptions = {}): Uint8Array => {
sign: (message: HexString | string | Uint8Array, options: SignOptions = {}): Uint8Array => {
assert(!isLocked(secretKey), 'Cannot sign with a locked key pair');
return u8aConcat(
@@ -207,10 +209,10 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
unlock: (passphrase?: string): void => {
return decodePkcs8(passphrase);
},
verify: (message: string | Uint8Array, signature: Uint8Array, _signerPublic: string | Uint8Array): boolean => {
return signatureVerify(message, signature, TYPE_ADDRESS[type](u8aToU8a(_signerPublic))).isValid;
verify: (message: HexString | string | Uint8Array, signature: HexString | string | Uint8Array, signerPublic: HexString | string | Uint8Array): boolean => {
return signatureVerify(message, signature, TYPE_ADDRESS[type](u8aToU8a(signerPublic))).isValid;
},
vrfSign: (message: string | Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): Uint8Array => {
vrfSign: (message: HexString | string | Uint8Array, context?: HexString | string | Uint8Array, extra?: string | Uint8Array): Uint8Array => {
assert(!isLocked(secretKey), 'Cannot sign with a locked key pair');
if (type === 'sr25519') {
@@ -221,14 +223,12 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
return u8aConcat(vrfHash(proof, context, extra), proof);
},
vrfVerify: (message: string | Uint8Array, vrfResult: Uint8Array, _signerPublic: Uint8Array | string, context?: string | Uint8Array, extra?: string | Uint8Array): boolean => {
const signerPublic = TYPE_ADDRESS[type](u8aToU8a(_signerPublic));
vrfVerify: (message: HexString | string | Uint8Array, vrfResult: Uint8Array, signerPublic: HexString | Uint8Array | string, context?: HexString | string | Uint8Array, extra?: HexString | string | Uint8Array): boolean => {
if (type === 'sr25519') {
return schnorrkelVrfVerify(message, vrfResult, publicKey, context, extra);
}
const result = signatureVerify(message, u8aConcat(TYPE_PREFIX[type], vrfResult.subarray(32)), signerPublic);
const result = signatureVerify(message, u8aConcat(TYPE_PREFIX[type], vrfResult.subarray(32)), TYPE_ADDRESS[type](u8aToU8a(signerPublic)));
return result.isValid && u8aEq(vrfResult.subarray(0, 32), vrfHash(vrfResult.subarray(32), context, extra));
}
+50 -48
View File
@@ -7,10 +7,12 @@ import { encodeAddress } from '@polkadot/util-crypto';
const publicKey = new Uint8Array(32);
const address = encodeAddress(publicKey);
const meta = {
isTesting: true,
name: 'nobody'
};
const json: KeyringPair$Json = {
address,
encoded: '',
@@ -22,54 +24,54 @@ const json: KeyringPair$Json = {
meta
};
export function nobody (): KeyringPair {
const pair: KeyringPair = {
address,
addressRaw: publicKey,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
decodePkcs8: (passphrase?: string, encoded?: Uint8Array): void =>
undefined,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
decryptMessage: (encryptedMessageWithNonce: string | Uint8Array, senderPublicKey: string | Uint8Array): Uint8Array | null =>
null,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
derive: (suri: string, meta?: KeyringPair$Meta): KeyringPair =>
pair,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
encodePkcs8: (passphrase?: string): Uint8Array =>
new Uint8Array(0),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
encryptMessage: (message: string | Uint8Array, recipientPublicKey: string | Uint8Array, _nonce?: Uint8Array): Uint8Array =>
new Uint8Array(),
isLocked: true,
lock: (): void => {
// no locking, it is always locked
},
meta,
publicKey,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
setMeta: (meta: KeyringPair$Meta): void =>
undefined,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
sign: (message: Uint8Array): Uint8Array =>
new Uint8Array(64),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
toJson: (passphrase?: string): KeyringPair$Json =>
json,
type: 'ed25519',
// eslint-disable-next-line @typescript-eslint/no-unused-vars
unlock: (passphrase?: string): void =>
undefined,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
verify: (message: Uint8Array, signature: Uint8Array): boolean =>
false,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
vrfSign: (message: Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): Uint8Array =>
new Uint8Array(96),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
vrfVerify: (message: Uint8Array, vrfResult: Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): boolean =>
false
};
const pair: KeyringPair = {
address,
addressRaw: publicKey,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
decodePkcs8: (passphrase?: string, encoded?: Uint8Array): void =>
undefined,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
decryptMessage: (encryptedMessageWithNonce: string | Uint8Array, senderPublicKey: string | Uint8Array): Uint8Array | null =>
null,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
derive: (suri: string, meta?: KeyringPair$Meta): KeyringPair =>
pair,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
encodePkcs8: (passphrase?: string): Uint8Array =>
new Uint8Array(0),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
encryptMessage: (message: string | Uint8Array, recipientPublicKey: string | Uint8Array, _nonce?: Uint8Array): Uint8Array =>
new Uint8Array(),
isLocked: true,
lock: (): void => {
// no locking, it is always locked
},
meta,
publicKey,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
setMeta: (meta: KeyringPair$Meta): void =>
undefined,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
sign: (message: Uint8Array): Uint8Array =>
new Uint8Array(64),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
toJson: (passphrase?: string): KeyringPair$Json =>
json,
type: 'ed25519',
// eslint-disable-next-line @typescript-eslint/no-unused-vars
unlock: (passphrase?: string): void =>
undefined,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
verify: (message: Uint8Array, signature: Uint8Array): boolean =>
false,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
vrfSign: (message: Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): Uint8Array =>
new Uint8Array(96),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
vrfVerify: (message: Uint8Array, vrfResult: Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): boolean =>
false
};
export function nobody (): KeyringPair {
return pair;
}
+3 -2
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { KeyringPair, KeyringPairs } from './types';
import { assert, isHex, isU8a, u8aToHex, u8aToU8a } from '@polkadot/util';
@@ -21,7 +22,7 @@ export class Pairs implements KeyringPairs {
return Object.values(this.#map);
}
public get (address: string | Uint8Array): KeyringPair {
public get (address: HexString | string | Uint8Array): KeyringPair {
const pair = this.#map[decodeAddress(address).toString()];
assert(pair, () => `Unable to retrieve keypair '${
@@ -33,7 +34,7 @@ export class Pairs implements KeyringPairs {
return pair;
}
public remove (address: string | Uint8Array): void {
public remove (address: HexString | string | Uint8Array): void {
delete this.#map[decodeAddress(address).toString()];
}
}
+21 -8
View File
@@ -3,12 +3,15 @@
// From https://github.com/paritytech/substrate/wiki/Secret-URI-Test-Vectors
import type { KeypairType } from '@polkadot/util-crypto/types';
import { u8aToHex } from '@polkadot/util';
import { cryptoWaitReady } from '@polkadot/util-crypto';
import Keyring from '.';
const PHRASE = 'bottom drive obey lake curtain smoke basket hold race lonely fit walk';
const ETHEREUM_PHRASE = 'seed sock milk update focus rotate barely fade car face mechanic mercy';
const TESTS = {
ecdsa: [
@@ -22,7 +25,17 @@ const TESTS = {
{
pk: '0x0381351b1b46d2602b0992bb5d5531f9c1696b0812feb2534b6884adc47e2e1d8b',
ss: '0x31ea8795EE32D782C8ff41a5C68Dcbf0F5B27f6d',
uri: "seed sock milk update focus rotate barely fade car face mechanic mercy/m/44'/60'/0'/0/0"
uri: `${ETHEREUM_PHRASE}/m/44'/60'/0'/0/0`
},
{
pk: '0x02509540919faacf9ab52146c9aa40db68172d83777250b28e4679176e49ccdd9f',
ss: '0xf24FF3a9CF04c71Dbc94D0b566f7A27B94566cac',
uri: `${PHRASE}/m/44'/60'/0'/0/0`
},
{
pk: '0x033bc19e36ff1673910575b6727a974a9abd80c9a875d41ab3e2648dbfb9e4b518',
ss: '0x3Cd0A705a2DC65e5b1E1205896BaA2be8A07c6e0',
uri: `${PHRASE}/m/44'/60'/0'/0/1`
}
],
sr25519: [
@@ -75,17 +88,17 @@ const TESTS = {
};
describe('keyring.addFromUri', (): void => {
const keyring = new Keyring({ type: 'sr25519' });
beforeEach(async (): Promise<void> => {
await cryptoWaitReady();
});
Object.entries(TESTS).forEach(([type, tests]): void => {
const keyring = new Keyring({ type: type as KeypairType });
beforeEach(async (): Promise<void> => {
await cryptoWaitReady();
});
describe(type, (): void => {
tests.forEach(({ pk, ss, uri }): void => {
it(`creates ${uri}`, (): void => {
const pair = keyring.addFromUri(uri, {}, type as 'sr25519');
const pair = keyring.addFromUri(uri, {}, type as KeypairType);
expect(u8aToHex(pair.publicKey)).toEqual(pk);
expect(pair.address).toEqual(ss);
+8 -10
View File
@@ -6,13 +6,13 @@ import type { KeyringInstance, KeyringOptions } from './types';
import { hexToU8a } from '@polkadot/util';
import { KeypairType } from '@polkadot/util-crypto/types';
import { Keyring } from './keyring';
import { createPair } from './pair';
import Keyring from '.';
interface PairDef {
name?: string;
publicKey: Uint8Array;
seed: string;
seed?: string;
secretKey?: Uint8Array;
type: KeypairType
}
@@ -77,42 +77,36 @@ export const PAIRSETHEREUM: PairDef[] = [
name: 'Alith',
publicKey: hexToU8a('0x02509540919faacf9ab52146c9aa40db68172d83777250b28e4679176e49ccdd9f'),
secretKey: hexToU8a('0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133'), // nosemgrep
seed: "m/44'/40'/0'/0",
type: 'ethereum'
},
{
name: 'Baltathar',
publicKey: hexToU8a('0x033bc19e36ff1673910575b6727a974a9abd80c9a875d41ab3e2648dbfb9e4b518'),
secretKey: hexToU8a('0x8075991ce870b93a8870eca0c0f91913d12f47948ca0fd25b49c6fa7cdbeee8b'), // nosemgrep
seed: "m/44'/40'/0'/0",
type: 'ethereum'
},
{
name: 'Charleth',
publicKey: hexToU8a('0x0234637bdc0e89b5d46543bcbf8edff329d2702bc995e27e9af4b1ba009a3c2a5e'),
secretKey: hexToU8a('0x0b6e18cafb6ed99687ec547bd28139cafdd2bffe70e6b688025de6b445aa5c5b'), // nosemgrep
seed: "m/44'/40'/0'/0",
type: 'ethereum'
},
{
name: 'Dorothy',
publicKey: hexToU8a('0x02a00d60b2b408c2a14c5d70cdd2c205db8985ef737a7e55ad20ea32cc9e7c417c'),
secretKey: hexToU8a('0x39539ab1876910bbf3a223d84a29e28f1cb4e2e456503e7e91ed39b2e7223d68'), // nosemgrep
seed: "m/44'/40'/0'/0",
type: 'ethereum'
},
{
name: 'Ethan',
publicKey: hexToU8a('0x025cdc005b752651cd3f728fb9192182acb3a9c89e19072cbd5b03f3ee1f1b3ffa'),
secretKey: hexToU8a('0x7dce9bc8babb68fec1409be38c8e1a52650206a7ed90ff956ae8a6d15eeaaef4'), // nosemgrep
seed: "m/44'/40'/0'/0",
type: 'ethereum'
},
{
name: 'Faith',
publicKey: hexToU8a('0x037964b6c9d546da4646ada28a99e34acaa1d14e7aba861a9055f9bd200c8abf74'),
secretKey: hexToU8a('0xb9d2ea9a615f3165812e8d44de0d24da9bbd164b65c4f0573e1ce2c8dbd9c8df'), // nosemgrep
seed: "m/44'/40'/0'/0",
type: 'ethereum'
}
];
@@ -128,11 +122,15 @@ export function createTestKeyring (options: KeyringOptions = {}, isDerived = tru
const pairs: PairDef[] = (options.type && options.type === 'ethereum') ? PAIRSETHEREUM : PAIRSSR25519;
pairs.forEach(({ name, publicKey, secretKey, seed, type }): void => {
if (!name && !seed) {
throw new Error('Testing pair should have either a name or a seed');
}
const meta = {
isTesting: true,
name: name || seed.replace('//', '_').toLowerCase()
name: name || (seed && seed.replace('//', '_').toLowerCase())
};
const pair = !isDerived && !name
const pair = !isDerived && !name && seed
? keyring.addFromUri(seed, meta, options.type)
: keyring.addPair(
createPair({ toSS58: keyring.encodeAddress, type }, { publicKey, secretKey }, meta)
+9 -10
View File
@@ -1,9 +1,8 @@
// Copyright 2017-2021 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Prefix } from '@polkadot/util-crypto/address/types';
import type { EncryptedJson } from '@polkadot/util-crypto/json/types';
import type { Keypair, KeypairType } from '@polkadot/util-crypto/types';
import type { HexString } from '@polkadot/util/types';
import type { EncryptedJson, Keypair, KeypairType, Prefix } from '@polkadot/util-crypto/types';
export interface KeyringOptions {
ss58Format?: Prefix;
@@ -13,7 +12,7 @@ export interface KeyringOptions {
export type KeyringPair$Meta = Record<string, unknown>;
export interface KeyringPair$Json extends EncryptedJson {
address: string;
address: string | HexString;
meta: KeyringPair$Meta;
}
@@ -34,14 +33,14 @@ export interface KeyringPair {
encodePkcs8 (passphrase?: string): Uint8Array;
lock (): void;
setMeta (meta: KeyringPair$Meta): void;
sign (message: string | Uint8Array, options?: SignOptions): Uint8Array;
sign (message: HexString | string | Uint8Array, options?: SignOptions): Uint8Array;
toJson (passphrase?: string): KeyringPair$Json;
unlock (passphrase?: string): void;
encryptMessage (message: string | Uint8Array, recipientPublicKey: string | Uint8Array, nonce?: Uint8Array): Uint8Array;
decryptMessage (encryptedMessageWithNonce: string | Uint8Array, senderPublicKey: string | Uint8Array): Uint8Array | null;
verify (message: string | Uint8Array, signature: Uint8Array, signerPublic: string | Uint8Array): boolean;
vrfSign (message: string | Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): Uint8Array;
vrfVerify (message: string | Uint8Array, vrfResult: Uint8Array, signerPublic: Uint8Array | string, context?: string | Uint8Array, extra?: string | Uint8Array): boolean;
encryptMessage (message: HexString | string | Uint8Array, recipientPublicKey: HexString | string | Uint8Array, nonce?: Uint8Array): Uint8Array;
decryptMessage (encryptedMessageWithNonce: HexString | string | Uint8Array, senderPublicKey: HexString | string | Uint8Array): Uint8Array | null;
verify (message: HexString | string | Uint8Array, signature: Uint8Array, signerPublic: HexString | string | Uint8Array): boolean;
vrfSign (message: HexString | string | Uint8Array, context?: HexString | string | Uint8Array, extra?: HexString | string | Uint8Array): Uint8Array;
vrfVerify (message: HexString | string | Uint8Array, vrfResult: Uint8Array, signerPublic: HexString | Uint8Array | string, context?: HexString | string | Uint8Array, extra?: HexString | string | Uint8Array): boolean;
}
export interface KeyringPairs {
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/networks",
"version": "7.1.2",
"version": "7.6.1",
"type": "module",
"description": "A list of all available Substrate networks and their applicable prefixes",
"main": "index.js",
@@ -16,10 +16,10 @@
"bugs": "https://github.com/polkadot-js/common/issues",
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/networks#readme",
"dependencies": {
"@babel/runtime": "^7.14.8"
"@babel/runtime": "^7.15.4"
},
"devDependencies": {
"@polkadot/util": "7.1.2",
"@polkadot/x-fetch": "7.1.2"
"@polkadot/util": "7.6.1",
"@polkadot/x-fetch": "7.6.1"
}
}
+21 -8
View File
@@ -4,20 +4,27 @@
import fs from 'fs';
import fetch from 'node-fetch';
const SUBSTRATE_REGISTRY = 'https://raw.githubusercontent.com/paritytech/substrate/master/ss58-registry.json';
import { substrateRegistry } from '../build/defaults.js';
function outputField (v) {
const substrateRegistryRepo = substrateRegistry
.replace('raw.githubusercontent.com', 'github.com')
.split('main')[0];
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;
}
async function getSubstrateRegistry () {
const original = await fetch(SUBSTRATE_REGISTRY);
const original = await fetch(substrateRegistry);
const json = await original.json();
return json.registry
@@ -25,7 +32,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');
@@ -36,11 +43,17 @@ getSubstrateRegistry()
fs.writeFileSync('packages/networks/src/substrate.ts', `// Copyright 2017-2021 @polkadot/networks authors & contributors
// SPDX-License-Identifier: Apache-2.0
//
// Auto-generated by yarn networks:sync (via scripts/fromSubstrate.mjs)
//
// Do not edit, rather
// - make a PR to the upstream registry as per ${SUBSTRATE_REGISTRY}
// - yarn networks:sync
// This file should never be edited manually. Rather the process is as follow -
//
// - make a PR to the upstream registry found at ${substrateRegistryRepo}
// - ensure the PR gets merged
// - yarn networks:sync in this repo to sync
//
// Any manual changes to this file will make CI cron checks fail and will be
// lost when the registry is updated alongside the above sync.
//
import type { KnownSubstrate } from './types';
+7 -3
View File
@@ -8,10 +8,10 @@ import fs from 'fs';
import { stringify } from '@polkadot/util';
import { fetch } from '@polkadot/x-fetch';
import { substrateRegistry } from './defaults';
import { allNetworks } from './';
const OUTPUT = './.github/ss58-check.md';
const SUBSTRATE_REGISTRY = 'https://raw.githubusercontent.com/paritytech/substrate/master/ss58-registry.json';
function assertAndLog (check: boolean, error: string): void {
if (!check) {
@@ -28,7 +28,7 @@ describe('check latest Substrate ss58 registry', (): void => {
let original: Ss58Registry;
beforeAll(async (): Promise<void> => {
original = (await (await fetch(SUBSTRATE_REGISTRY)).json()) as Ss58Registry;
original = (await (await fetch(substrateRegistry)).json()) as Ss58Registry;
});
it('has the same number as the original', (): void => {
@@ -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])
)
: []
];
})
+14
View File
@@ -3,11 +3,16 @@
import type { KnownGenesis, KnownIcon, KnownLedger, KnownTestnet } from './types';
export const substrateRegistry = 'https://raw.githubusercontent.com/paritytech/ss58-registry/main/ss58-registry.json';
// NOTE: In the case where the network was hard-spooned and multiple genesisHashes
// are provided, it needs to be in reverse order, i.e. most-recent first, oldest
// 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 +42,9 @@ export const knownGenesis: KnownGenesis = {
'0xe3777fa922cafbff200cadeaea1a76bd7898ad5b89f7848999058b50e715f636', // Kusama CC2
'0x3fd7b9eb6a00376e5be61f01abb429ffb0b104be05eaff4d458da48fcd425baf' // Kusama CC1
],
'nodle-chain': [
'0xa3d114c2b8d0627c1aa9b134eafcf7d05ca561fdc19fb388bb9457f81809fb23'
],
plasm: [
'0x3e86364d4b4894021cb2a0390bcf2feb5517d5292f2de2bb9404227e908b0b8b'
],
@@ -46,6 +54,9 @@ export const knownGenesis: KnownGenesis = {
polymesh: [
'0x9deeb940c92ae02111c3bd5baca89970384f4c9849f02a1b2e53e66414d30f9f'
],
stafi: [
'0x290a4149f09ea0e402c74c1c7e96ae4239588577fe78932f94f5404c68243d80'
],
statemine: [
'0x48239ef607d7928874027a43a67689209727dfb3d3dc5e5b03a39bdc2eda771a'
],
@@ -73,6 +84,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
@@ -80,6 +92,8 @@ export const knownLedger: KnownLedger = {
// testnets should not allow selection
export const knownTestnet: KnownTestnet = {
'': true, // this is the default non-network entry
'cess-testnet': true,
'dock-testnet': true,
jupiter: true,
'mathchain-testnet': true,
+1 -1
View File
@@ -18,7 +18,7 @@ export const allNetworks = knownSubstrate.map((o): SubstrateNetwork => {
n.genesisHash = knownGenesis[network] || [];
n.icon = knownIcon[network] || 'substrate';
n.isIgnored = !network || !!knownTestnet[network] || network.startsWith('reserved');
n.isIgnored = !!knownTestnet[network] || (!(o.standardAccount && o.decimals && o.symbols) && o.prefix !== 42);
return n;
});
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/networks', version: '7.1.2' };
export const packageInfo = { name: '@polkadot/networks', version: '7.6.1' };
+102 -15
View File
@@ -1,11 +1,17 @@
// Copyright 2017-2021 @polkadot/networks authors & contributors
// SPDX-License-Identifier: Apache-2.0
//
// Auto-generated by yarn networks:sync (via scripts/fromSubstrate.mjs)
//
// Do not edit, rather
// - make a PR to the upstream registry as per https://raw.githubusercontent.com/paritytech/substrate/master/ss58-registry.json
// - yarn networks:sync
// This file should never be edited manually. Rather the process is as follow -
//
// - make a PR to the upstream registry found at https://github.com/paritytech/ss58-registry/
// - ensure the PR gets merged
// - yarn networks:sync in this repo to sync
//
// Any manual changes to this file will make CI cron checks fail and will be
// lost when the registry is updated alongside the above sync.
//
import type { KnownSubstrate } from './types';
@@ -23,9 +29,9 @@ export const knownSubstrate: KnownSubstrate[] = [
{
decimals: null,
displayName: 'Bare 32-bit Schnorr/Ristretto (S/R 25519) public key.',
network: null,
network: 'BareSr25519',
prefix: 1,
standardAccount: null,
standardAccount: 'Sr25519',
symbols: null,
website: null
},
@@ -41,9 +47,9 @@ export const knownSubstrate: KnownSubstrate[] = [
{
decimals: null,
displayName: 'Bare 32-bit Ed25519 public key.',
network: null,
network: 'BareEd25519',
prefix: 3,
standardAccount: null,
standardAccount: 'Ed25519',
symbols: null,
website: null
},
@@ -129,13 +135,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,14 +393,14 @@ export const knownSubstrate: KnownSubstrate[] = [
prefix: 42,
standardAccount: '*25519',
symbols: null,
website: 'https://substrate.dev/'
website: 'https://substrate.io/'
},
{
decimals: null,
displayName: 'Bare 32-bit ECDSA SECP-256k1 public key.',
network: null,
network: 'BareSecp256k1',
prefix: 43,
standardAccount: null,
standardAccount: 'secp256k1',
symbols: null,
website: null
},
@@ -443,6 +449,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 +539,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 +584,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',
@@ -578,6 +629,15 @@ export const knownSubstrate: KnownSubstrate[] = [
symbols: ['NET'],
website: 'https://social.network'
},
{
decimals: [15],
displayName: 'QUARTZ by UNIQUE',
network: 'quartz_mainnet',
prefix: 255,
standardAccount: '*25519',
symbols: ['QTZ'],
website: 'https://unique.network'
},
{
decimals: [18],
displayName: 'Moonbeam',
@@ -604,5 +664,32 @@ export const knownSubstrate: KnownSubstrate[] = [
standardAccount: '*25519',
symbols: ['BSX'],
website: 'https://bsx.fi'
},
{
decimals: [12],
displayName: 'CESS Testnet',
network: 'cess-testnet',
prefix: 10042,
standardAccount: '*25519',
symbols: ['TCESS'],
website: 'https://cess.cloud'
},
{
decimals: [12],
displayName: 'CESS',
network: 'cess',
prefix: 10043,
standardAccount: '*25519',
symbols: ['CESS'],
website: 'https://cess.cloud'
},
{
decimals: [18],
displayName: 'Automata ContextFree',
network: 'contextfree',
prefix: 11820,
standardAccount: '*25519',
symbols: ['CTX'],
website: 'https://ata.network'
}
];
+1 -1
View File
@@ -8,7 +8,7 @@ export interface KnownSubstrate {
displayName: string;
network: string | null;
prefix: number;
standardAccount: '*25519' | 'secp256k1' | null;
standardAccount: '*25519' | 'Ed25519' | 'Sr25519' | 'secp256k1' | null;
symbols: string[] | null;
website: string | null;
}
+9 -9
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/util-crypto",
"version": "7.1.2",
"version": "7.6.1",
"type": "module",
"description": "A collection of useful crypto utilities for @polkadot",
"main": "index.js",
@@ -21,15 +21,15 @@
"bugs": "https://github.com/polkadot-js/common/issues",
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util-crypto#readme",
"dependencies": {
"@babel/runtime": "^7.14.8",
"@polkadot/networks": "7.1.2",
"@polkadot/util": "7.1.2",
"@polkadot/wasm-crypto": "^4.1.2",
"@polkadot/x-randomvalues": "7.1.2",
"base-x": "^3.0.8",
"@babel/runtime": "^7.15.4",
"@polkadot/networks": "7.6.1",
"@polkadot/util": "7.6.1",
"@polkadot/wasm-crypto": "^4.2.1",
"@polkadot/x-randomvalues": "7.6.1",
"base-x": "^3.0.9",
"base64-js": "^1.5.1",
"blakejs": "^1.1.1",
"bn.js": "^4.11.9",
"bn.js": "^4.12.0",
"create-hash": "^1.2.0",
"ed2curve": "^0.3.0",
"elliptic": "^6.5.4",
@@ -47,6 +47,6 @@
"@types/xxhashjs": "^0.2.2"
},
"peerDependencies": {
"@polkadot/util": "7.1.2"
"@polkadot/util": "7.6.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;
+2 -6
View File
@@ -1,17 +1,13 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { validateChars } from '../base58/validate';
import { createValidateFn } from '../base58/validate';
import { BASE32_ALPHABET } from './bs32';
const BASE_CONFIG = { alphabet: BASE32_ALPHABET, ipfsChar: 'b', type: 'base32' };
/**
* @name base32Validate
* @summary Validates a base32 value.
* @description
* Validates that the supplied value is valid base32
*/
export function base32Validate (value?: string | null, ipfsCompat?: boolean): value is string {
return validateChars(BASE_CONFIG, value, ipfsCompat);
}
export const base32Validate = createValidateFn({ alphabet: BASE32_ALPHABET, ipfsChar: 'b', type: 'base32' });
+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
+10 -12
View File
@@ -11,17 +11,17 @@ interface CheckConfig {
type: string;
}
const BASE_CONFIG = { alphabet: BASE58_ALPHABET, ipfsChar: 'z', type: 'base58' };
export function createValidateFn ({ alphabet, ipfsChar, type }: CheckConfig): (value?: unknown, ipfsCompat?: boolean) => value is string {
return (value?: unknown, ipfsCompat?: boolean): value is string => {
assert(value && typeof value === 'string', () => `Expected non-null, non-empty ${type} string input`);
assert(!ipfsCompat || value[0] === ipfsChar, () => `Expected ${type} to start with '${ipfsChar}'`);
export function validateChars ({ alphabet, ipfsChar, type }: CheckConfig, value?: unknown, ipfsCompat?: boolean): true {
assert(value && typeof value === 'string', () => `Expected non-null, non-empty ${type} string input`);
assert(!ipfsCompat || value[0] === ipfsChar, () => `Expected ${type} to start with '${ipfsChar}'`);
for (let i = (ipfsCompat ? 1 : 0); i < value.length; i++) {
assert(alphabet.includes(value[i]), () => `Invalid ${type} character "${value[i]}" (0x${value.charCodeAt(i).toString(16)}) at index ${i}`);
}
for (let i = (ipfsCompat ? 1 : 0); i < value.length; i++) {
assert(alphabet.includes(value[i]), () => `Invalid ${type} character "${value[i]}" (0x${value.charCodeAt(i).toString(16)}) at index ${i}`);
}
return true;
return true;
};
}
/**
@@ -30,6 +30,4 @@ export function validateChars ({ alphabet, ipfsChar, type }: CheckConfig, value?
* @description
* Validates that the supplied value is valid base58
*/
export function base58Validate (value?: string | null, ipfsCompat?: boolean): value is string {
return validateChars(BASE_CONFIG, value, ipfsCompat);
}
export const base58Validate = createValidateFn({ alphabet: BASE58_ALPHABET, ipfsChar: 'z', type: 'base58' });
+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)) {
@@ -0,0 +1,18 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Keypair } from '../types';
import { assert } from '@polkadot/util';
import { DeriveJunction } from './DeriveJunction';
export function createSeedDeriveFn (fromSeed: (seed: Uint8Array) => Keypair, derive: (seed: Uint8Array, chainCode: Uint8Array) => Uint8Array): (keypair: Keypair, junction: DeriveJunction) => Keypair {
return (keypair: Keypair, { chainCode, isHard }: DeriveJunction): Keypair => {
assert(isHard, 'A soft key was found in the path and is not supported');
return fromSeed(
derive(keypair.secretKey.subarray(0, 32), chainCode)
);
};
}
+2 -12
View File
@@ -1,18 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Keypair } from '../types';
import { assert } from '@polkadot/util';
import { secp256k1DeriveHard } from '../secp256k1/deriveHard';
import { secp256k1KeypairFromSeed } from '../secp256k1/keypair/fromSeed';
import { DeriveJunction } from './DeriveJunction';
import { createSeedDeriveFn } from './hdkdDerive';
export function keyHdkdEcdsa (keypair: Keypair, { chainCode, isHard }: DeriveJunction): Keypair {
assert(isHard, 'A soft key was found in the path (and is unsupported)');
return secp256k1KeypairFromSeed(
secp256k1DeriveHard(keypair.secretKey.subarray(0, 32), chainCode)
);
}
export const keyHdkdEcdsa = createSeedDeriveFn(secp256k1KeypairFromSeed, secp256k1DeriveHard);
+2 -12
View File
@@ -1,18 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Keypair } from '../types';
import { assert } from '@polkadot/util';
import { naclDeriveHard } from '../nacl/deriveHard';
import { naclKeypairFromSeed } from '../nacl/keypair/fromSeed';
import { DeriveJunction } from './DeriveJunction';
import { createSeedDeriveFn } from './hdkdDerive';
export function keyHdkdEd25519 (keypair: Keypair, { chainCode, isHard }: DeriveJunction): Keypair {
assert(isHard, 'A soft key was found in the path (and is unsupported)');
return naclKeypairFromSeed(
naclDeriveHard(keypair.secretKey.subarray(0, 32), chainCode)
);
}
export const keyHdkdEd25519 = createSeedDeriveFn(naclKeypairFromSeed, naclDeriveHard);
+2 -2
View File
@@ -10,7 +10,7 @@
// - Adjust formatting (just eslint differences)
// - Only English wordlist (this aligns with the wasm-crypto implementation)
// - Use util-crypto randomAsU8a (instead of randombytes)
// - Remove setting of wordlost passing of wordlist in functions
// - Remove setting of wordlist passing of wordlist in functions
// - Remove mnemonicToSeed (we only use the sync variant)
import hash from 'hash.js';
@@ -34,7 +34,7 @@ function binaryToByte (bin: string): number {
}
function bytesToBinary (bytes: number[]): string {
return bytes.map((x: number) => x.toString(2).padStart(8, '0')).join('');
return bytes.map((x) => x.toString(2).padStart(8, '0')).join('');
}
function deriveChecksumBits (entropyBuffer: Uint8Array): string {
@@ -8,7 +8,7 @@ import { mnemonicToSeedSync } from './bip39';
import { mnemonicValidate } from './validate';
/**
* @name toSeed
* @name mnemonicToLegacySeed
* @summary Creates a valid Ethereum/Bitcoin-compatible seed from a mnemonic input
* @example
* <BR>
@@ -28,13 +28,13 @@ export function mnemonicToLegacySeed (mnemonic: string, password = '', onlyJs =
assert(mnemonicValidate(mnemonic), 'Invalid bip39 mnemonic specified');
assert([32, 64].includes(byteLength), () => `Invalid seed length ${byteLength}, expected 32 or 64`);
if (byteLength && byteLength === 32) {
if (byteLength === 32) {
return isReady() && !onlyJs
? bip39ToSeed(mnemonic, password)
: mnemonicToSeedSync(mnemonic, password).subarray(0, 32);
} else if (byteLength === 64) {
return mnemonicToSeedSync(mnemonic, password);
} else {
return new Uint8Array();
}
return new Uint8Array();
}
+2 -1
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../types';
import nacl from 'tweetnacl';
@@ -22,7 +23,7 @@ import { ed25519Sign, isReady } from '@polkadot/wasm-crypto';
* naclSign([...], [...]); // => [...]
* ```
*/
export function naclSign (message: Uint8Array | string, { publicKey, secretKey }: Partial<Keypair>, onlyJs = false): Uint8Array {
export function naclSign (message: HexString | Uint8Array | string, { publicKey, secretKey }: Partial<Keypair>, onlyJs = false): Uint8Array {
assert(secretKey, 'Expected a valid secretKey');
const messageU8a = u8aToU8a(message);
+3 -1
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import nacl from 'tweetnacl';
import { assert, u8aToU8a } from '@polkadot/util';
@@ -20,7 +22,7 @@ import { ed25519Verify, isReady } from '@polkadot/wasm-crypto';
* naclVerify([...], [...], [...]); // => true/false
* ```
*/
export function naclVerify (message: Uint8Array | string, signature: Uint8Array | string, publicKey: Uint8Array | string, onlyJs = false): boolean {
export function naclVerify (message: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, publicKey: HexString | Uint8Array | string, onlyJs = false): boolean {
const messageU8a = u8aToU8a(message);
const publicKeyU8a = u8aToU8a(publicKey);
const signatureU8a = u8aToU8a(signature);
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/util-crypto', version: '7.1.2' };
export const packageInfo = { name: '@polkadot/util-crypto', version: '7.6.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,20 @@
// 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 { schnorrkelKeypairFromU8a } from './keypair/fromU8a';
import { schnorrkelKeypairToU8a } from './keypair/toU8a';
export function createDeriveFn (derive: (pair: Uint8Array, cc: Uint8Array) => Uint8Array): (keypair: Keypair, chainCode: HexString | Uint8Array | string) => Keypair {
return (keypair: Keypair, chainCode: HexString | Uint8Array | string) =>
schnorrkelKeypairFromU8a(
derive(
schnorrkelKeypairToU8a(keypair),
u8aToU8a(chainCode)
)
);
}
@@ -1,15 +1,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Keypair } from '../types';
import { sr25519DeriveKeypairHard } from '@polkadot/wasm-crypto';
import { schnorrkelKeypairFromU8a } from './keypair/fromU8a';
import { schnorrkelKeypairToU8a } from './keypair/toU8a';
import { createDeriveFn } from './derive';
export function schnorrkelDeriveHard (keypair: Keypair, chainCode: Uint8Array): Keypair {
return schnorrkelKeypairFromU8a(
sr25519DeriveKeypairHard(schnorrkelKeypairToU8a(keypair), chainCode)
);
}
export const schnorrkelDeriveHard = createDeriveFn(sr25519DeriveKeypairHard);
@@ -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,8 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Keypair } from '../types';
import { sr25519DeriveKeypairSoft } from '@polkadot/wasm-crypto';
import { schnorrkelKeypairFromU8a } from './keypair/fromU8a';
import { schnorrkelKeypairToU8a } from './keypair/toU8a';
import { createDeriveFn } from './derive';
export function schnorrkelDeriveSoft (keypair: Keypair, chainCode: Uint8Array): Keypair {
return schnorrkelKeypairFromU8a(
sr25519DeriveKeypairSoft(schnorrkelKeypairToU8a(keypair), chainCode)
);
}
export const schnorrkelDeriveSoft = createDeriveFn(sr25519DeriveKeypairSoft);
@@ -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(
@@ -9,7 +9,7 @@ import { secp256k1 } from './secp256k1';
*/
export function secp256k1Recover (message: Uint8Array, signature: Uint8Array, recovery: number): Uint8Array {
return new Uint8Array(
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-argument
secp256k1
.recoverPubKey(message, { r: signature.slice(0, 32), s: signature.slice(32, 64) }, recovery)
.encode(null, true)
+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 { HashType } from './types';
import { assert, u8aEq, u8aToU8a } from '@polkadot/util';
@@ -13,14 +14,14 @@ 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);
assert(u8a.length === 65, `Expected signature with 65 bytes, ${u8a.length} found instead`);
const publicKey = new Uint8Array(
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-argument
secp256k1
.recoverPubKey(
secp256k1Hasher(hashType, message),
@@ -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)
);
+8 -5
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,18 +22,19 @@ 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);
const u8a = u8aToU8a(data);
if (isReady() && !onlyJs) {
return twox(u8aToU8a(data), iterations);
return twox(u8a, iterations);
}
const u8a = new Uint8Array(Math.ceil(bitLength / 8));
const result = new Uint8Array(Math.ceil(bitLength / 8));
for (let seed = 0; seed < iterations; seed++) {
u8a.set(xxhash64AsBn(data, seed).toArray('le', 8), seed * 8);
result.set(xxhash64AsBn(u8a, seed).toArray('le', 8), seed * 8);
}
return u8a;
return result;
}
@@ -3,15 +3,11 @@
import xx from 'xxhashjs';
import { isBuffer, isString, u8aToBuffer } from '@polkadot/util';
import { u8aToU8a } from '@polkadot/util';
export default function xxhash64AsValue (data: Buffer | Uint8Array | string, seed: number): number {
if (isBuffer(data) || isString(data)) {
return xx.h64(data, seed);
}
return xx.h64(
u8aToBuffer(data),
u8aToU8a(data).buffer,
seed
);
}
+1 -1
View File
@@ -3,7 +3,7 @@
declare module 'xxhashjs' {
export interface HashInterface {
(data: string | Buffer, seed: number): number;
(data: string | Buffer | ArrayBuffer, seed: number): number;
}
const h64: HashInterface;
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/util",
"version": "7.1.2",
"version": "7.6.1",
"type": "module",
"description": "A collection of useful utilities for @polkadot",
"main": "index.js",
@@ -19,12 +19,12 @@
"bugs": "https://github.com/polkadot-js/common/issues",
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util#readme",
"dependencies": {
"@babel/runtime": "^7.14.8",
"@polkadot/x-textdecoder": "7.1.2",
"@polkadot/x-textencoder": "7.1.2",
"@babel/runtime": "^7.15.4",
"@polkadot/x-textdecoder": "7.6.1",
"@polkadot/x-textencoder": "7.6.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;
}

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