Compare commits

...
96 Commits
Author SHA1 Message Date
Github Actions 39937bed29 [CI Skip] release/stable 7.9.2
skip-checks: true
2021-11-22 05:16:31 +00:00
Jaco 3519d21d8e 7.9.2 (#1227) 2021-11-22 07:12:03 +02:00
Github Actions 8b4dc01ae4 [CI Skip] release/beta 7.9.2-2
skip-checks: true
2021-11-22 04:56:09 +00:00
Jaco bb73f7ae41 Fix TS import generation (#1226)
* Fix TS import generation

* Flatten
2021-11-22 06:51:49 +02:00
Github Actions e6a0f1e2fd [CI Skip] release/beta 7.9.2-1
skip-checks: true
2021-11-21 18:25:15 +00:00
Jaco e8af9b5a1e Add a helper for de-dupe of *AsHex (#1224)
* Add a helper for de-dupe of *AsHex

* Update packages/util-crypto/src/random/asU8a.ts

* lint

* isWasmOnly helper

* bit hasher
2021-11-21 20:21:20 +02:00
Github Actions 1606dfd9ca [CI Skip] release/beta 7.9.2-0
skip-checks: true
2021-11-21 06:58:47 +00:00
Jaco 2fcf59eeb0 Provide JS/Wasm interfaces for hmacShaAsU8a (#1223)
* Provide JS/Wasm interfaces for hmacShaAsU8a

* Adjust

* Re-add helpers

* Alignments
2021-11-21 08:54:54 +02:00
Github Actions a7606b6514 [CI Skip] release/stable 7.9.1
skip-checks: true
2021-11-21 05:26:30 +00:00
Jaco 871b20c90a 7.9.1 (#1222) 2021-11-21 07:22:56 +02:00
Github Actions 5d93642093 [CI Skip] release/beta 7.8.3-41
skip-checks: true
2021-11-20 16:30:44 +00:00
Jaco 2b2fefb2bb Basic rountrip tests for mmacSha (#1221) 2021-11-20 18:27:06 +02:00
Github Actions 1ede65db38 [CI Skip] release/beta 7.8.3-40
skip-checks: true
2021-11-20 07:33:41 +00:00
Jaco 7090c3daec Re-use cleanups (#1219)
* Re-use cleanups

* linting

* Adjust

* Adjust

* ipfsCompat into if

* Adjust
2021-11-20 09:29:13 +02:00
Github Actions c03f53e097 [CI Skip] release/beta 7.8.3-39
skip-checks: true
2021-11-19 15:50:17 +00:00
Jaco 2ec02e2580 Combine sha256/512 into single top-level folder (#1218)
* Combine sha256/512 into single top-level folder

* linting

* imports
2021-11-19 17:46:49 +02:00
Github Actions 6b4f9b3d2f [CI Skip] release/beta 7.8.3-38
skip-checks: true
2021-11-19 14:21:02 +00:00
Jaco d20c37ddd0 Extract performance test loop (& bump wasm) (#1217)
* Extract performance test loop (& bump wasm)

* bitLength for blake preformance

* sha512 naming

* ops/s display
2021-11-19 16:16:39 +02:00
Github Actions 23d46b063c [CI Skip] release/beta 7.8.3-37
skip-checks: true
2021-11-19 13:03:22 +00:00
Jaco 085862ce79 Wasm-compat for keccak512 & sha256 (#1216)
* Wasm-compa for keccak512 & sha256

* wasm/non-wasm tests

* linting

* Bump wasm

* formatting
2021-11-19 14:59:59 +02:00
Github Actions 88580b98a6 [CI Skip] release/beta 7.8.3-36
skip-checks: true
2021-11-19 12:05:22 +00:00
Jaco fb8b80afd7 Add/use sha256 export (#1215) 2021-11-19 14:01:19 +02:00
Github Actions d3b5b4ad38 [CI Skip] release/beta 7.8.3-35
skip-checks: true
2021-11-19 11:41:37 +00:00
Jaco 049e8dfde8 Curve conversion tests (#1214) 2021-11-19 13:37:43 +02:00
Github Actions 8230e3ceac [CI Skip] release/beta 7.8.3-34
skip-checks: true
2021-11-19 11:27:04 +00:00
Jaco 37358d4d05 Correct location for @types/ed2curve (#1213) 2021-11-19 13:22:59 +02:00
Github Actions 2cf6ffa3b1 [CI Skip] release/beta 7.8.3-33
skip-checks: true
2021-11-19 10:59:25 +00:00
Jaco d7f2a70071 networks:sync (#1212) 2021-11-19 12:54:59 +02:00
Github Actions eb96e2a7aa [CI Skip] release/beta 7.8.3-32
skip-checks: true
2021-11-19 09:38:49 +00:00
Jaco 6965709351 Drop unused BigInt class extension (#1210) 2021-11-19 11:35:05 +02:00
Github Actions 1677d3eace [CI Skip] release/beta 7.8.3-31
skip-checks: true
2021-11-19 09:31:53 +00:00
Jaco 4d77bf3c5b Use micro-base for base{32, 58, 64} (#1209) 2021-11-19 11:27:47 +02:00
Github Actions 222bb74a81 [CI Skip] release/beta 7.8.3-30
skip-checks: true
2021-11-19 07:59:15 +00:00
Jaco 90b4b61852 Add has* env detection (#1207) 2021-11-19 09:55:17 +02:00
Github Actions b1e209dfeb [CI Skip] release/beta 7.8.3-29
skip-checks: true
2021-11-19 04:27:06 +00:00
Jaco 88beb4d81c Adjust isHex length check (#1205) 2021-11-19 06:23:01 +02:00
Github Actions 3b2ecb87e9 [CI Skip] release/beta 7.8.3-28
skip-checks: true
2021-11-18 16:18:37 +00:00
Adam Dossa 79a2cd0e8f Update Polymesh Genesis Hash (#1193) 2021-11-18 18:14:35 +02:00
Github Actions 0c2d105f9d [CI Skip] release/beta 7.8.3-27
skip-checks: true
2021-11-18 08:26:04 +00:00
Jaco 944d77c5f2 Bump deps (#1202) 2021-11-18 10:21:54 +02:00
Github Actions 0fdf83effe [CI Skip] release/beta 7.8.3-26
skip-checks: true
2021-11-18 08:01:33 +00:00
Jaco 66866e1a8e isCodec (#1201) 2021-11-18 09:57:26 +02:00
Github Actions 9abcc72143 [CI Skip] release/beta 7.8.3-25
skip-checks: true
2021-11-18 06:52:13 +00:00
Jaco 6f0aa35098 Flatten calls (#1200) 2021-11-18 08:48:15 +02:00
Github Actions 93fb633ea6 [CI Skip] release/beta 7.8.3-24
skip-checks: true
2021-11-17 12:11:04 +00:00
Jaco 5524e50baf stripPrefix adjustment 2021-11-17 14:07:43 +02:00
Jaco e1354746b1 Fix hexStripPrefix 2021-11-17 14:01:04 +02:00
Github Actions 309722f285 [CI Skip] release/beta 7.8.3-23
skip-checks: true
2021-11-17 11:52:13 +00:00
Jaco 4efd88869d Re-add ignoreLength (#1199)
* Re-add ignoreLength

* Actual ignore
2021-11-17 13:48:07 +02:00
Github Actions ee0436a612 [CI Skip] release/beta 7.8.3-22
skip-checks: true
2021-11-17 08:37:01 +00:00
Jaco b4ca8219d9 Sync ss58 registry (#1198) 2021-11-17 10:33:28 +02:00
Github Actions d30a3ddedb [CI Skip] release/beta 7.8.3-21
skip-checks: true
2021-11-16 18:31:05 +00:00
Jaco fa5b5bca7e Additional bigint utilities (#1194)
* Additional bigint utilities

* Adjust tests

* biTo{Hex, U8a}

* Adjust

* Ordering

* biSqrt

* Fix toU8a

* Extensible BigInt

* Class TS issues....

* Move type def to types

* Update packages/util/src/bi/sqrt.spec.ts

* max/min

* min/max tests
2021-11-16 20:27:19 +02:00
Github Actions 87afdb1d86 [CI Skip] release/beta 7.8.3-20
skip-checks: true
2021-11-16 04:38:40 +00:00
Jaco 23f68c63f4 Constant for secp256k1 curve.n (#1192)
* Constant for secp256k1 curve.n

* Link to constant definition

* global space replace
2021-11-16 06:35:25 +02:00
Github Actions 184dbccf39 [CI Skip] release/beta 7.8.3-19
skip-checks: true
2021-11-15 18:50:53 +00:00
Jaco 06c06a8b73 toBigInt utilities (#1191)
* toBigInt utilities

* Handle negatives?

* two's complement adjustments

* Adjust

* Compliment util extract

* dedupe

* Ensure > u32 tests
2021-11-15 20:46:48 +02:00
Github Actions 82f5fec822 [CI Skip] release/beta 7.8.3-18
skip-checks: true
2021-11-15 14:36:07 +00:00
Jaco a953b3a78a Optimize bip39 list for size (#1190) 2021-11-15 16:32:48 +02:00
Github Actions 19283b3c28 [CI Skip] release/beta 7.8.3-17
skip-checks: true
2021-11-15 12:34:06 +00:00
Jaco ac06f38118 Bump deps (#1187) 2021-11-15 14:30:31 +02:00
Github Actions f9e5c033ab [CI Skip] release/beta 7.8.3-16
skip-checks: true
2021-11-15 11:05:50 +00:00
Jaco de7817e6b5 Use DataView as applicable (#1186)
* Use DataView as applicable

* .skip

* Fix hexToU8a length calc

* hello world
2021-11-15 13:01:47 +02:00
Github Actions 5972551313 [CI Skip] release/beta 7.8.3-15
skip-checks: true
2021-11-15 05:19:33 +00:00
Jaco cf0aab479a Small utility adjustments (#1185) 2021-11-15 07:16:21 +02:00
Github Actions 5ab0b173b6 [CI Skip] release/beta 7.8.3-14
skip-checks: true
2021-11-14 19:07:34 +00:00
Jaco cf990dd4ec Aligh u8aToHex optimization (#1184)
* Aligh u8aToHex optimization

* Adjust

* Fix failing tests, empty value

* Adjust

* numberToHex fix

* Fix hexFixLength tests
2021-11-14 21:03:41 +02:00
Github Actions 8a6fd0812a [CI Skip] release/beta 7.8.3-13
skip-checks: true
2021-11-14 17:26:15 +00:00
Jaco e93f8d7418 for look index namings (consistency) (#1183) 2021-11-14 19:22:06 +02:00
Github Actions 36f6407796 [CI Skip] release/beta 7.8.3-12
skip-checks: true
2021-11-14 15:39:05 +00:00
Jaco 8ede488aec u8aEq w/ U32 and lower only (#1182)
* u8aEq w/ U32 and lower only

* Adjust mod

* Adjust signatures
2021-11-14 17:35:56 +02:00
Github Actions eb9d5b9585 [CI Skip] release/beta 7.8.3-11
skip-checks: true
2021-11-14 15:25:32 +00:00
Jaco 20821aad40 Performance optimizations (#1181)
* Performance optimizations

* Use slice internally to u8aEq

* Adjust

* formatting

* subarray

* Fixes

* Use DataView

* With alignment

* Use Float64Array when available

* Skip performance

* Renames

* Alignment comment

* Constants

* Use BYTES_PER_ELEMENT

* Adjust
2021-11-14 17:21:07 +02:00
Github Actions 23fa2b90a8 [CI Skip] release/beta 7.8.3-10
skip-checks: true
2021-11-13 17:37:15 +00:00
Jaco f94a1ea730 ss58 sync (#1180) 2021-11-13 19:34:08 +02:00
Github Actions fc98cd9b45 [CI Skip] release/beta 7.8.3-9
skip-checks: true
2021-11-13 15:43:42 +00:00
Jaco 5fdd967666 Small consistency cleanups (#1178)
* Small consistency cleanups

* Adjust

* Adjust
2021-11-13 17:39:52 +02:00
Github Actions 9043f335d4 [CI Skip] release/beta 7.8.3-8
skip-checks: true
2021-11-13 09:42:20 +00:00
Jaco d9231d26aa Additional Node-specific u8a utils (#1177)
* Additional Node-specific u8a utils

* toHexBuffer
2021-11-13 11:38:07 +02:00
Github Actions 445e0f7ea6 [CI Skip] release/beta 7.8.3-7
skip-checks: true
2021-11-12 07:23:46 +00:00
Jaco ba0a183bd9 Re-use pre-define BN_{BE, LE}_* constants (#1175)
* Re-use pre-define BN_{BE, LE}_* constants

* ordering update

* bnMax/bnMin opt

* u8aToHex flatten
2021-11-12 09:19:49 +02:00
Github Actions 46beaa1151 [CI Skip] release/beta 7.8.3-6
skip-checks: true
2021-11-12 06:47:36 +00:00
Jaco 31d55b218a Additional tests (w/ lazy) (#1174) 2021-11-12 08:44:00 +02:00
Github Actions 9b30b4b09e [CI Skip] release/beta 7.8.3-5
skip-checks: true
2021-11-11 13:45:03 +00:00
Jaco cc0dd2a2b5 Address validation tests (#1173) 2021-11-11 15:41:54 +02:00
Github Actions 31a0a9b9d1 [CI Skip] release/beta 7.8.3-4
skip-checks: true
2021-11-11 13:23:30 +00:00
Jaco 9e1e49a1b8 Additional tests (need to expand more...) (#1172)
* Additional utility tests

* Args on constructor
2021-11-11 15:20:01 +02:00
Github Actions 313b44388a [CI Skip] release/beta 7.8.3-3
skip-checks: true
2021-11-11 12:42:42 +00:00
Jaco 30dd8169bc Add tests missing for object* methods (#1171)
* Add tests missing for object* methods

* Extend objectProperty comments

* Additional test

* objectProperties this test

* Adjust
2021-11-11 14:38:58 +02:00
Github Actions 67450bc225 [CI Skip] release/beta 7.8.3-2
skip-checks: true
2021-11-11 12:06:01 +00:00
Jaco e9285e9ccd Bump deps (#1170) 2021-11-11 14:02:11 +02:00
Github Actions 2a45652ce0 [CI Skip] release/beta 7.8.3-1
skip-checks: true
2021-11-08 08:16:48 +00:00
Jaco 6d923da266 object{Entries, Keys, Values} (#1169)
* object{Entries, Keys, Values}

* Use objectKeys as applicable

* tighten schema defs

* Linting issue snuck in
2021-11-08 10:09:26 +02:00
Github Actions d55b48566b [CI Skip] release/beta 7.8.3-0
skip-checks: true
2021-11-08 06:11:13 +00:00
Jaco 3ac567e1c4 stringPascalCase (#1168) 2021-11-08 08:03:04 +02:00
Jaco d19713f548 hexToU8aBuffer 2021-11-08 08:02:36 +02:00
253 changed files with 5851 additions and 1285 deletions
+2 -1
View File
@@ -18,4 +18,5 @@
7.0.2
7.0.3
7.1.2
7.8.2
7.8.2
7.9.2
+31
View File
@@ -1,5 +1,36 @@
# CHANGELOG
## 7.9.2 Nov 22, 2021
Changes:
- Fix TS compiled definitions for `base*` types
- Provide JS/Wasm interfaces for `hmacShaAsU8a`
## 7.9.1 Nov 21, 2021
Contributed:
- Updated Polymesh genesisHash (Thanks to https://github.com/adamdossa)
Changes:
- Add strongly typed `object{Entries, Keys, Values}` utilities
- Add `{hex, u8a}ToBigInt` utilities
- Add `bi*` utilities for `bigint` operations (mirror of `bn*`)
- Add `stringPascalCase` utility
- Add `isCodec` to check for Codec-like structures
- Add `has*` detection shortcuts (e.g. `hasWasm` or `hasBuffer`)
- Add `sha256AsU8a` util (& replace use internally)
- Optimize for `hexToU8a` and `u8aToHex` functions
- Optimize `u8aEq` to use `DataView` for compares
- Align `base{32, 58, 64}*` around (audited) `micro-base`
- Space optimization for bip39 wordlists
- Sync with upstream Substrate ss58 registry
- Expand tests for uncovered functions
## 7.8.2 Nov 7, 2021
Changes:
+5 -6
View File
@@ -10,7 +10,7 @@
"url": "https://github.com/polkadot-js/common.git"
},
"sideEffects": false,
"version": "7.8.2",
"version": "7.9.2",
"workspaces": [
"packages/*"
],
@@ -29,12 +29,11 @@
},
"devDependencies": {
"@babel/core": "^7.16.0",
"@polkadot/dev": "^0.63.27",
"@polkadot/ts": "^0.4.13",
"@types/ed2curve": "^0.2.2",
"@types/jest": "^27.0.2"
"@polkadot/dev": "^0.63.29",
"@polkadot/ts": "^0.4.14",
"@types/jest": "^27.0.3"
},
"resolutions": {
"typescript": "^4.4.4"
"typescript": "^4.5.2"
}
}
+2 -2
View File
@@ -16,12 +16,12 @@
},
"sideEffects": false,
"type": "module",
"version": "7.8.2",
"version": "7.9.2",
"browser": "browser.js",
"main": "node.js",
"react-native": "react-native.js",
"dependencies": {
"@babel/runtime": "^7.16.0",
"@babel/runtime": "^7.16.3",
"@ledgerhq/hw-transport": "^6.11.2",
"@ledgerhq/hw-transport-webhid": "^6.11.2",
"@ledgerhq/hw-transport-webusb": "^6.11.2"
@@ -10,13 +10,6 @@ import LedgerWebUsb from '@ledgerhq/hw-transport-webusb';
export { packageInfo } from './packageInfo';
export const transports: TransportDef[] = [
// deprecated
// import LedgerU2F from '@ledgerhq/hw-transport-u2f';
// {
// create: (): Promise<Transport> =>
// LedgerU2F.create(),
// type: 'u2f'
// },
{
create: (): Promise<Transport> =>
LedgerWebUsb.create(),
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/hw-ledger-transports', version: '7.8.2' };
export const packageInfo = { name: '@polkadot/hw-ledger-transports', version: '7.9.2' };
+4 -4
View File
@@ -19,12 +19,12 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "7.8.2",
"version": "7.9.2",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.16.0",
"@polkadot/hw-ledger-transports": "7.8.2",
"@polkadot/util": "7.8.2",
"@babel/runtime": "^7.16.3",
"@polkadot/hw-ledger-transports": "7.9.2",
"@polkadot/util": "7.9.2",
"@zondax/ledger-substrate": "^0.18.0"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/hw-ledger', version: '7.8.2' };
export const packageInfo = { name: '@polkadot/hw-ledger', version: '7.9.2' };
+6 -6
View File
@@ -20,15 +20,15 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "7.8.2",
"version": "7.9.2",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.16.0",
"@polkadot/util": "7.8.2",
"@polkadot/util-crypto": "7.8.2"
"@babel/runtime": "^7.16.3",
"@polkadot/util": "7.9.2",
"@polkadot/util-crypto": "7.9.2"
},
"peerDependencies": {
"@polkadot/util": "7.8.2",
"@polkadot/util-crypto": "7.8.2"
"@polkadot/util": "7.9.2",
"@polkadot/util-crypto": "7.9.2"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/keyring', version: '7.8.2' };
export const packageInfo = { name: '@polkadot/keyring', version: '7.9.2' };
+1 -1
View File
@@ -13,7 +13,7 @@ interface PairStateJson {
}
export function pairToJson (type: KeypairType, { address, meta }: PairStateJson, encoded: Uint8Array, isEncrypted: boolean): KeyringPair$Json {
return objectSpread({}, jsonEncryptFormat(encoded, ['pkcs8', type], isEncrypted), {
return objectSpread(jsonEncryptFormat(encoded, ['pkcs8', type], isEncrypted), {
address,
meta
});
+4 -4
View File
@@ -17,13 +17,13 @@
},
"sideEffects": false,
"type": "module",
"version": "7.8.2",
"version": "7.9.2",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.16.0"
"@babel/runtime": "^7.16.3"
},
"devDependencies": {
"@polkadot/util": "7.8.2",
"@polkadot/x-fetch": "7.8.2"
"@polkadot/util": "7.9.2",
"@polkadot/x-fetch": "7.9.2"
}
}
+3 -3
View File
@@ -1,11 +1,11 @@
// Copyright 2017-2021 @polkadot/networks authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { KnownSubstrate, Ss58Registry } from './types';
import type { Ss58Registry } from './types';
import fs from 'fs';
import { stringify } from '@polkadot/util';
import { objectKeys, stringify } from '@polkadot/util';
import { fetch } from '@polkadot/x-fetch';
import { substrateRegistry } from './defaults';
@@ -52,7 +52,7 @@ describe('check latest Substrate ss58 registry', (): void => {
});
it('has the same values as the original', (): void => {
const fields = Object.keys(original.schema) as (keyof KnownSubstrate)[];
const fields = objectKeys(original.schema);
const errors = original.registry
.map((n): [string, string[]] => {
const other = allNetworks.find(({ prefix }) => prefix === n.prefix);
+2 -1
View File
@@ -58,7 +58,7 @@ export const knownGenesis: KnownGenesis = {
'0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'
],
polymesh: [
'0x9deeb940c92ae02111c3bd5baca89970384f4c9849f02a1b2e53e66414d30f9f'
'0x6fbd74e5e1d0a61d52ccfe9d4adaed16dd3a7caa37c6bc4d0c2fa12e8b2f4063'
],
stafi: [
'0x290a4149f09ea0e402c74c1c7e96ae4239588577fe78932f94f5404c68243d80'
@@ -104,5 +104,6 @@ export const knownTestnet: KnownTestnet = {
'dock-testnet': true,
jupiter: true,
'mathchain-testnet': true,
subspace_testnet: true,
'zero-alphaville': true
};
+1 -1
View File
@@ -3,4 +3,4 @@
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/networks', version: '7.8.2' };
export const packageInfo = { name: '@polkadot/networks', version: '7.9.2' };
+46 -1
View File
@@ -149,7 +149,7 @@ export const knownSubstrate: KnownSubstrate[] = [
network: 'totem',
prefix: 14,
standardAccount: '*25519',
symbols: ['XTX'],
symbols: ['TOTEM'],
website: 'https://totemaccounting.com'
},
{
@@ -467,6 +467,15 @@ export const knownSubstrate: KnownSubstrate[] = [
symbols: ['LAYR'],
website: 'https://composable.finance'
},
{
decimals: [9],
displayName: 'xx network',
network: 'xxnetwork',
prefix: 55,
standardAccount: '*25519',
symbols: ['XX'],
website: 'https://xx.network'
},
{
decimals: [12],
displayName: 'HydraDX',
@@ -575,6 +584,15 @@ export const knownSubstrate: KnownSubstrate[] = [
symbols: ['TRAC'],
website: 'https://origintrail.io'
},
{
decimals: [10],
displayName: 'Pontem Network',
network: 'pontem-network',
prefix: 105,
standardAccount: '*25519',
symbols: ['PONT'],
website: 'https://pontem.network'
},
{
decimals: [12],
displayName: 'Heiko',
@@ -665,6 +683,33 @@ export const knownSubstrate: KnownSubstrate[] = [
symbols: ['MOVR'],
website: 'https://moonbeam.network'
},
{
decimals: [12],
displayName: 'Kapex',
network: 'kapex',
prefix: 2007,
standardAccount: '*25519',
symbols: ['KAPEX'],
website: 'https://totemaccounting.com'
},
{
decimals: [18],
displayName: 'Subspace testnet',
network: 'subspace_testnet',
prefix: 2254,
standardAccount: '*25519',
symbols: ['tSSC'],
website: 'https://subspace.network'
},
{
decimals: [18],
displayName: 'Subspace',
network: 'subspace',
prefix: 6094,
standardAccount: '*25519',
symbols: ['SSC'],
website: 'https://subspace.network'
},
{
decimals: [12],
displayName: 'Basilisk',
+1 -1
View File
@@ -37,5 +37,5 @@ export interface Network extends SubstrateNetwork {
export interface Ss58Registry {
registry: KnownSubstrate[];
specification: string;
schema: Record<string, string>;
schema: Record<keyof KnownSubstrate, string>;
}
+9 -9
View File
@@ -22,16 +22,14 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "7.8.2",
"version": "7.9.2",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.16.0",
"@polkadot/networks": "7.8.2",
"@polkadot/util": "7.8.2",
"@polkadot/wasm-crypto": "^4.2.1",
"@polkadot/x-randomvalues": "7.8.2",
"base-x": "^3.0.9",
"base64-js": "^1.5.1",
"@babel/runtime": "^7.16.3",
"@polkadot/networks": "7.9.2",
"@polkadot/util": "7.9.2",
"@polkadot/wasm-crypto": "^4.4.1",
"@polkadot/x-randomvalues": "7.9.2",
"blakejs": "^1.1.1",
"bn.js": "^4.12.0",
"create-hash": "^1.2.0",
@@ -39,6 +37,7 @@
"elliptic": "^6.5.4",
"hash.js": "^1.1.7",
"js-sha3": "^0.8.0",
"micro-base": "^0.9.0",
"scryptsy": "^2.1.0",
"tweetnacl": "^1.0.3",
"xxhashjs": "^0.2.2"
@@ -46,11 +45,12 @@
"devDependencies": {
"@types/bn.js": "^4.11.6",
"@types/create-hash": "^1.2.2",
"@types/ed2curve": "^0.2.2",
"@types/elliptic": "^6.4.14",
"@types/scryptsy": "^2.0.0",
"@types/xxhashjs": "^0.2.2"
},
"peerDependencies": {
"@polkadot/util": "7.8.2"
"@polkadot/util": "7.9.2"
}
}
+1 -1
View File
@@ -4,7 +4,7 @@
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types';
import { base58Decode } from '../base58/decode';
import { base58Decode } from '../base58';
import { checkAddressChecksum } from './checksum';
import { defaults } from './defaults';
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { base58Decode } from '../base58/decode';
import { base58Decode } from '../base58';
import { checkAddressChecksum } from './checksum';
describe('checkAddressChecksum', (): void => {
+1 -1
View File
@@ -7,7 +7,7 @@ import type { Prefix } from './types';
// Original implementation: https://github.com/paritytech/polka-ui/blob/4858c094684769080f5811f32b081dd7780b0880/src/polkadot.js#L6
import { assert, isHex, isU8a, u8aToU8a } from '@polkadot/util';
import { base58Decode } from '../base58/decode';
import { base58Decode } from '../base58';
import { checkAddressChecksum } from './checksum';
import { defaults } from './defaults';
+1 -1
View File
@@ -7,7 +7,7 @@ import type { Prefix } from './types';
// Original implementation: https://github.com/paritytech/polka-ui/blob/4858c094684769080f5811f32b081dd7780b0880/src/polkadot.js#L34
import { assert, u8aConcat } from '@polkadot/util';
import { base58Encode } from '../base58/encode';
import { base58Encode } from '../base58';
import { decodeAddress } from './decode';
import { defaults } from './defaults';
import { sshash } from './sshash';
+111
View File
@@ -0,0 +1,111 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { isAddress } from '.';
describe('isAddress', (): void => {
it('decodes an address', (): void => {
expect(
isAddress('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY')
).toEqual(true);
});
it('decodes the council address', (): void => {
expect(
isAddress('F3opxRbN5ZbjJNU511Kj2TLuzFcDq9BGduA9TgiECafpg29')
).toEqual(true);
});
it('converts a publicKey (hex) as-is', (): void => {
expect(
isAddress('0x01020304')
).toEqual(true);
});
it('decodes a short address', (): void => {
expect(
isAddress('F7NZ')
).toEqual(true);
});
it('decodes a 1-byte accountId (with prefix)', (): void => {
expect(
isAddress('g4b', false, 2)
).toEqual(true);
});
it('decodes a 2-byte accountId', (): void => {
expect(
isAddress('3xygo', false, 2)
).toEqual(true);
});
it('encodes a 4-byte address', (): void => {
expect(
isAddress('zswfoZa', false, 2)
).toEqual(true);
});
it('decodes a 8-byte address', (): void => {
expect(
isAddress('848Gh2GcGaZia', false, 2)
).toEqual(true);
});
it('decodes a 33-byte address', (): void => {
expect(
isAddress('KWCv1L3QX9LDPwY4VzvLmarEmXjVJidUzZcinvVnmxAJJCBou')
).toEqual(true);
});
it('decodes a 2-byte prefix (65)', (): void => {
expect(
isAddress('cLtA6nCDyvwKcEHH4QkZDSHMhS9s78BvUJUsKUbUAn1Jc2SCF')
).toEqual(true);
});
it('decodes a 2-byte prefix (69)', (): void => {
expect(
isAddress('cnUaoo5wodnTVA4bnr4woSweto8hWZADUvLFXkR9Q6U7BRsbF')
).toEqual(true);
});
it('decodes a 2-byte prefix (252)', (): void => {
expect(
isAddress('xw9Hca4RJTmBRgzJT4ieJBh7XCK9gE3NXBDSEmgGHd4TCrbnG')
).toEqual(true);
});
it('decodes a 2-byte prefix (255)', (): void => {
expect(
isAddress('yGHU8YKprxHbHdEv7oUK4rzMZXtsdhcXVG2CAMyC9WhzhjH2k')
).toEqual(true);
});
it('decodes a 2-byte prefix (ecdsa, from Substrate)', (): void => {
expect(
isAddress('4pbsSkWcBaYoFHrKJZp5fDVUKbqSYD9dhZZGvpp3vQ5ysVs5ybV')
).toEqual(true);
});
it('fails when length is invalid', (): void => {
expect(
isAddress('y9EMHt34JJo4rWLSaxoLGdYXvjgSXEd4zHUnQgfNzwES8b')
).toEqual(false);
});
it('fails when the checksum does not match', (): void => {
expect(
isAddress('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMa9cj')
).toEqual(false);
expect(
isAddress('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDwU')
).toEqual(false);
});
it('fails when invalid base58 encoded address is found', (): void => {
expect(
isAddress('F3opIRbN5ZbjJNU511Kj2TLuzFcDq9BGduA9TgiECafpg29')
).toEqual(false);
});
});
@@ -7,6 +7,7 @@ import type { HexString } from '@polkadot/util/types';
import { bnToU8a, stringToU8a, u8aConcat } from '@polkadot/util';
import { blake2AsU8a } from '../blake2/asU8a';
import { BN_LE_16_OPTS } from '../bn';
import { decodeAddress } from './decode';
const PREFIX = stringToU8a('modlpy/utilisuba');
@@ -16,7 +17,7 @@ export function createKeyDerived (who: HexString | Uint8Array | string, index: b
u8aConcat(
PREFIX,
decodeAddress(who),
bnToU8a(index, { bitLength: 16, isLe: true })
bnToU8a(index, BN_LE_16_OPTS)
)
);
}
+2 -1
View File
@@ -7,6 +7,7 @@ import type { HexString } from '@polkadot/util/types';
import { bnToU8a, compactToU8a, stringToU8a, u8aConcat, u8aSorted } from '@polkadot/util';
import { blake2AsU8a } from '../blake2/asU8a';
import { BN_LE_16_OPTS } from '../bn';
import { addressToU8a } from './util';
const PREFIX = stringToU8a('modlpy/utilisuba');
@@ -17,7 +18,7 @@ export function createKeyMulti (who: (HexString | Uint8Array | string)[], thresh
PREFIX,
compactToU8a(who.length),
...u8aSorted(who.map(addressToU8a)),
bnToU8a(threshold, { bitLength: 16, isLe: true })
bnToU8a(threshold, BN_LE_16_OPTS)
)
);
}
@@ -0,0 +1,111 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { validateAddress } from '.';
describe('validateAddress', (): void => {
it('decodes an address', (): void => {
expect(
validateAddress('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY')
).toEqual(true);
});
it('decodes the council address', (): void => {
expect(
validateAddress('F3opxRbN5ZbjJNU511Kj2TLuzFcDq9BGduA9TgiECafpg29')
).toEqual(true);
});
it('converts a publicKey (hex) as-is', (): void => {
expect(
validateAddress('0x01020304')
).toEqual(true);
});
it('decodes a short address', (): void => {
expect(
validateAddress('F7NZ')
).toEqual(true);
});
it('decodes a 1-byte accountId (with prefix)', (): void => {
expect(
validateAddress('g4b', false, 2)
).toEqual(true);
});
it('decodes a 2-byte accountId', (): void => {
expect(
validateAddress('3xygo', false, 2)
).toEqual(true);
});
it('encodes a 4-byte address', (): void => {
expect(
validateAddress('zswfoZa', false, 2)
).toEqual(true);
});
it('decodes a 8-byte address', (): void => {
expect(
validateAddress('848Gh2GcGaZia', false, 2)
).toEqual(true);
});
it('decodes a 33-byte address', (): void => {
expect(
validateAddress('KWCv1L3QX9LDPwY4VzvLmarEmXjVJidUzZcinvVnmxAJJCBou')
).toEqual(true);
});
it('decodes a 2-byte prefix (65)', (): void => {
expect(
validateAddress('cLtA6nCDyvwKcEHH4QkZDSHMhS9s78BvUJUsKUbUAn1Jc2SCF')
).toEqual(true);
});
it('decodes a 2-byte prefix (69)', (): void => {
expect(
validateAddress('cnUaoo5wodnTVA4bnr4woSweto8hWZADUvLFXkR9Q6U7BRsbF')
).toEqual(true);
});
it('decodes a 2-byte prefix (252)', (): void => {
expect(
validateAddress('xw9Hca4RJTmBRgzJT4ieJBh7XCK9gE3NXBDSEmgGHd4TCrbnG')
).toEqual(true);
});
it('decodes a 2-byte prefix (255)', (): void => {
expect(
validateAddress('yGHU8YKprxHbHdEv7oUK4rzMZXtsdhcXVG2CAMyC9WhzhjH2k')
).toEqual(true);
});
it('decodes a 2-byte prefix (ecdsa, from Substrate)', (): void => {
expect(
validateAddress('4pbsSkWcBaYoFHrKJZp5fDVUKbqSYD9dhZZGvpp3vQ5ysVs5ybV')
).toEqual(true);
});
it('fails when length is invalid', (): void => {
expect(
() => validateAddress('y9EMHt34JJo4rWLSaxoLGdYXvjgSXEd4zHUnQgfNzwES8b')
).toThrow(/address length/);
});
it('fails when the checksum does not match', (): void => {
expect(
() => validateAddress('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMa9cj')
).toThrow(/address checksum/);
expect(
() => validateAddress('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDwU')
).toThrow(/address checksum/);
});
it('fails when invalid base58 encoded address is found', (): void => {
expect(
() => validateAddress('F3opIRbN5ZbjJNU511Kj2TLuzFcDq9BGduA9TgiECafpg29')
).toThrow(/Decoding F3opIRbN5ZbjJNU511Kj2TLuzFcDq9BGduA9TgiECafpg29: Invalid base58 character "I" \(0x49\) at index 4/);
});
});
+50 -3
View File
@@ -1,6 +1,53 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
// https://github.com/multiformats/js-multibase/blob/master/src/constants.js
export const BASE32_ALPHABET = 'abcdefghijklmnopqrstuvwxyz234567';
export const BITS_PER_CHAR = 5;
import { utils } from 'micro-base';
import { createDecode, createEncode, createIs, createValidate } from './helpers';
const BASE32_ALPHABET = 'abcdefghijklmnopqrstuvwxyz234567';
const BASE32_CONFIG = {
alphabet: BASE32_ALPHABET,
coder: utils.chain(
// We define our own chain, the default base32 has padding
utils.radix2(5),
utils.alphabet(BASE32_ALPHABET),
{
decode: (input: string) => input.split(''),
encode: (input: string[]) => input.join('')
}
),
ipfsChar: 'b',
type: 'base32'
};
/**
* @name base32Validate
* @summary Validates a base32 value.
* @description
* Validates that the supplied value is valid base32, throwing exceptions if not
*/
export const base32Validate = createValidate(BASE32_CONFIG);
/**
* @name isBase32
* @description Checks if the input is in base32, returning true/false
*/
export const isBase32 = createIs(base32Validate);
/**
* @name base32Decode
* @summary Delookup a base32 value.
* @description
* From the provided input, decode the base32 and return the result as an `Uint8Array`.
*/
export const base32Decode = createDecode(BASE32_CONFIG, base32Validate);
/**
* @name base32Encode
* @summary Creates a base32 value.
* @description
* From the provided input, create the base32 and return the result as a string.
*/
export const base32Encode = createEncode(BASE32_CONFIG);
@@ -3,7 +3,7 @@
import { u8aToString } from '@polkadot/util';
import { base32Decode } from './';
import { base32Decode } from '.';
describe('base32Decode', (): void => {
it('decodes a base32', (): void => {
-56
View File
@@ -1,56 +0,0 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
// adapted from https://github.com/multiformats/js-multibase/blob/424709195b46ffb1d6f2f69a7707598ebe751e5e/src/rfc4648.js
import { assert } from '@polkadot/util';
import { BASE32_ALPHABET, BITS_PER_CHAR } from './bs32';
import { base32Validate } from './validate';
// Build the character lookup table:
const LOOKUP = BASE32_ALPHABET.split('').reduce<Record<string, number>>((lookup, a, i) => {
lookup[a] = i;
return lookup;
}, {});
/** @internal */
function decode (output: Uint8Array, input: string, offset: number): [Uint8Array, number, number] {
let bits = 0;
let buffer = 0;
let written = 0;
for (let i = offset; i < input.length; i++) {
buffer = (buffer << BITS_PER_CHAR) | LOOKUP[input[i]];
bits += BITS_PER_CHAR;
if (bits >= 8) {
bits -= 8;
output[written++] = 0xff & (buffer >> bits);
}
}
return [output, bits, buffer];
}
/**
* @name base32Decode
* @summary Delookup a base32 value.
* @description
* From the provided input, decode the base32 and return the result as an `Uint8Array`.
*/
export function base32Decode (value: string, ipfsCompat = false): Uint8Array {
base32Validate(value, ipfsCompat);
const offset = (ipfsCompat ? 1 : 0);
const [output, bits, buffer] = decode(
new Uint8Array(((value.length - offset) * BITS_PER_CHAR / 8) | 0),
value,
offset
);
assert(!(bits >= BITS_PER_CHAR || 0xff & (buffer << (8 - bits))), 'Unexpected end of data');
return output;
}
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import { base58Decode } from '../base58';
import { base32Encode } from './';
import { base32Encode } from '.';
describe('base32Encode', (): void => {
it('encodes to a base32', (): void => {
@@ -11,6 +11,12 @@ describe('base32Encode', (): void => {
).toEqual('irswgzloorzgc3djpjssazlwmvzhs5dinfxgoijb');
});
it('encodes to a base32 (ipfs-compat)', (): void => {
expect(
base32Encode('Decentralize everything!!', true)
).toEqual('birswgzloorzgc3djpjssazlwmvzhs5dinfxgoijb');
});
it('encodes a base58 to a base32', (): void => {
expect(
base32Encode(
-43
View File
@@ -1,43 +0,0 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
// 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';
const MASK = (1 << BITS_PER_CHAR) - 1;
/**
* @name base32Encode
* @summary Creates a base32 value.
* @description
* From the provided input, create the base32 and return the result as a string.
*/
export function base32Encode (value: U8aLike, ipfsCompat = false): string {
const u8a = u8aToU8a(value);
let out = '';
let bits = 0;
let buffer = 0;
for (let i = 0; i < u8a.length; ++i) {
buffer = (buffer << 8) | u8a[i];
bits += 8;
while (bits > BITS_PER_CHAR) {
bits -= BITS_PER_CHAR;
out += BASE32_ALPHABET[MASK & (buffer >> bits)];
}
}
if (bits) {
out += BASE32_ALPHABET[MASK & (buffer << (BITS_PER_CHAR - bits))];
}
return ipfsCompat
? `b${out}`
: out;
}
@@ -0,0 +1,87 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { assert, u8aToU8a } from '@polkadot/util';
// NOTE: Work around a TS issue. These are re-defined like in @polkadot/util/types
// since without it the import
//
// import type { U8aLike } from '@polkadot/util/types';
//
// ends up in the build-generated code as
//
// import("../../../util/src/types").U8aLike
//
// eslint-disable-next-line @typescript-eslint/ban-types
type U8aLike = number[] | Buffer | Uint8Array | string | String;
interface Coder {
decode: (value: string) => Uint8Array;
encode: (value: Uint8Array) => string;
}
interface Config {
alphabet: string;
coder: Coder;
ipfsChar?: string;
regex?: RegExp;
type: string;
}
type DecodeFn = (value: string, ipfsCompat?: boolean) => Uint8Array;
type EncodeFn = (value: U8aLike, ipfsCompat?: boolean) => string;
type ValidateFn = (value?: unknown, ipfsCompat?: boolean) => value is string;
export function createDecode ({ coder, ipfsChar }: Config, validate: ValidateFn): DecodeFn {
return (value: string, ipfsCompat?: boolean): Uint8Array => {
validate(value, ipfsCompat);
return coder.decode(
ipfsChar && ipfsCompat
? value.substr(1)
: value
);
};
}
export function createEncode ({ coder, ipfsChar }: Config): EncodeFn {
return (value: U8aLike, ipfsCompat?: boolean): string => {
const out = coder.encode(u8aToU8a(value));
return ipfsChar && ipfsCompat
? `${ipfsChar}${out}`
: out;
};
}
export function createIs (validate: ValidateFn): ValidateFn {
return (value?: unknown, ipfsCompat?: boolean): value is string => {
try {
return validate(value, ipfsCompat);
} catch (error) {
return false;
}
};
}
export function createValidate ({ alphabet, ipfsChar, regex, type }: Config): ValidateFn {
return (value?: unknown, ipfsCompat?: boolean): value is string => {
assert(value && typeof value === 'string', () => `Expected non-null, non-empty ${type} string input`);
if (ipfsChar && ipfsCompat) {
assert(value[0] === ipfsChar, () => `Expected ipfs-compatible ${type} to start with '${ipfsChar}'`);
}
if (regex) {
assert(regex.test(value), `Invalid ${type} encoding`);
} else {
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;
};
}
+1 -4
View File
@@ -5,7 +5,4 @@
* @summary Encode and decode base32 values
*/
export { base32Decode } from './decode';
export { base32Encode } from './encode';
export { base32Validate } from './validate';
export { isBase32 } from './is';
export { base32Decode, base32Encode, base32Validate, isBase32 } from './bs32';
@@ -0,0 +1,30 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { isBase32 } from '.';
describe('isBase32', (): void => {
it('validates encoded', (): void => {
expect(
isBase32('afkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', false)
).toEqual(true);
});
it('validates ipfs-compat encoded', (): void => {
expect(
isBase32('bafkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', false)
).toEqual(true);
});
it('fails on invalid', (): void => {
expect(
isBase32('not in base32')
).toEqual(false);
});
it('fails on non-ipfs', (): void => {
expect(
isBase32('afkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', true)
).toEqual(false);
});
});
-16
View File
@@ -1,16 +0,0 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { base32Validate } from './validate';
export function testValidator (validate: (value?: string | null, ipfsCompat?: boolean) => boolean, value?: string | null, ipfsCompat?: boolean): boolean {
try {
return validate(value, ipfsCompat);
} catch (error) {
return false;
}
}
export function isBase32 (value?: string | null, ipfsCompat?: boolean): value is string {
return testValidator(base32Validate, value, ipfsCompat);
}
@@ -4,9 +4,39 @@
import { base32Validate } from '.';
describe('base32Validate', (): void => {
it('validates encoded', (): void => {
expect(
base32Validate('afkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', false)
).toEqual(true);
});
it('validates ipfs-compat encoded', (): void => {
expect(
() => base32Validate('bafkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', true)
).not.toThrow();
base32Validate('bafkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', true)
).toEqual(true);
});
it('fails on empty', (): void => {
expect(
() => base32Validate('')
).toThrow(/Expected/);
});
it('fails on non-string', (): void => {
expect(
() => base32Validate(true)
).toThrow(/Expected/);
});
it('fails on invalid', (): void => {
expect(
() => base32Validate('not in base32')
).toThrow(/Invalid/);
});
it('fails on non-ipfs', (): void => {
expect(
() => base32Validate('afkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', true)
).toThrow(/Expected/);
});
});
@@ -1,13 +0,0 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { createValidateFn } from '../base58/validate';
import { BASE32_ALPHABET } from './bs32';
/**
* @name base32Validate
* @summary Validates a base32 value.
* @description
* Validates that the supplied value is valid base32
*/
export const base32Validate = createValidateFn({ alphabet: BASE32_ALPHABET, ipfsChar: 'b', type: 'base32' });
+38 -4
View File
@@ -1,9 +1,43 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import baseX from 'base-x';
import { base58 } from 'micro-base';
// https://github.com/cryptocoinjs/base-x#alphabets
export const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
import { createDecode, createEncode, createIs, createValidate } from '../base32/helpers';
export const bs58 = baseX(BASE58_ALPHABET);
const BASE58_CONFIG = {
alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz',
coder: base58,
ipfsChar: 'z',
type: 'base58'
};
/**
* @name base58Validate
* @summary Validates a base58 value.
* @description
* Validates that the supplied value is valid base58, throwing exceptions if not
*/
export const base58Validate = createValidate(BASE58_CONFIG);
/**
* @name base58Decode
* @summary Decodes a base58 value.
* @description
* From the provided input, decode the base58 and return the result as an `Uint8Array`.
*/
export const base58Decode = createDecode(BASE58_CONFIG, base58Validate);
/**
* @name base58Encode
* @summary Creates a base58 value.
* @description
* From the provided input, create the base58 and return the result as a string.
*/
export const base58Encode = createEncode(BASE58_CONFIG);
/**
* @name isBase58
* @description Checks if the input is in base58, returning true/false
*/
export const isBase58 = createIs(base58Validate);
@@ -0,0 +1,23 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { base32Decode } from '../base32';
import { base58Decode } from './';
describe('base58Encode', (): void => {
it('encodes a base58 to a base32', (): void => {
expect(
base58Decode('b2rhk6GMPQF3hfzwXTaNYFLKomMeC6UXdUt6jZKPpeVirLtV')
).toEqual(
base32Decode('afkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy')
);
});
it('encodes a base58 to a base32 (ipfs-compat)', (): void => {
expect(
base58Decode('zb2rhk6GMPQF3hfzwXTaNYFLKomMeC6UXdUt6jZKPpeVirLtV', true)
).toEqual(
base32Decode('bafkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', true)
);
});
});
-19
View File
@@ -1,19 +0,0 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { bufferToU8a } from '@polkadot/util';
import { bs58 } from './bs58';
import { base58Validate } from './validate';
/**
* @name base58Decode
* @summary Decodes a base58 value.
* @description
* From the provided input, decode the base58 and return the result as an `Uint8Array`.
*/
export function base58Decode (value: string, ipfsCompat?: boolean): Uint8Array {
base58Validate(value, ipfsCompat);
return bufferToU8a(bs58.decode(value.substr(ipfsCompat ? 1 : 0)));
}
@@ -5,7 +5,15 @@ import { base32Decode } from '../base32';
import { base58Encode } from './';
describe('base58Encode', (): void => {
it('encodes a base32 to a base38', (): void => {
it('encodes a base32 to a base58', (): void => {
expect(
base58Encode(
base32Decode('bafkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', true)
)
).toEqual('b2rhk6GMPQF3hfzwXTaNYFLKomMeC6UXdUt6jZKPpeVirLtV');
});
it('encodes a base32 to a base58 (ipfs-compat)', (): void => {
expect(
base58Encode(
base32Decode('bafkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', true),
-22
View File
@@ -1,22 +0,0 @@
// 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';
/**
* @name base58Encode
* @summary Creates a base58 value.
* @description
* From the provided input, create the base58 and return the result as a string.
*/
export function base58Encode (value: U8aLike, ipfsCompat?: boolean): string {
const out = bs58.encode(u8aToU8a(value));
return ipfsCompat
? `z${out}`
: out;
}
+1 -4
View File
@@ -5,7 +5,4 @@
* @summary Encode and decode base58 values
*/
export { base58Decode } from './decode';
export { base58Encode } from './encode';
export { base58Validate } from './validate';
export { isBase58 } from './is';
export { base58Decode, base58Encode, base58Validate, isBase58 } from './bs58';
-9
View File
@@ -1,9 +0,0 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { testValidator } from '../base32/is';
import { base58Validate } from './validate';
export function isBase58 (value?: string | null, ipfsCompat?: boolean): value is string {
return testValidator(base58Validate, value, ipfsCompat);
}
@@ -1,33 +0,0 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { assert } from '@polkadot/util';
import { BASE58_ALPHABET } from './bs58';
interface CheckConfig {
alphabet: string;
ipfsChar: string;
type: string;
}
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}'`);
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;
};
}
/**
* @name base58Validate
* @summary Validates a base58 value.
* @description
* Validates that the supplied value is valid base58
*/
export const base58Validate = createValidateFn({ alphabet: BASE58_ALPHABET, ipfsChar: 'z', type: 'base58' });
+43
View File
@@ -0,0 +1,43 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { base64 } from 'micro-base';
import { createDecode, createEncode, createIs, createValidate } from '../base32/helpers';
const BASE64_CONFIG = {
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
coder: base64,
regex: /^(?:[A-Za-z0-9+/]{2}[A-Za-z0-9+/]{2})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,
type: 'base64'
};
/**
* @name base64Validate
* @summary Validates a base64 value.
* @description
* Validates that the supplied value is valid base64
*/
export const base64Validate = createValidate(BASE64_CONFIG);
/**
* @name isBase64
* @description Checks if the input is in base64, returning true/false
*/
export const isBase64 = createIs(base64Validate);
/**
* @name base64Decode
* @summary Decodes a base64 value.
* @description
* From the provided input, decode the base64 and return the result as an `Uint8Array`.
*/
export const base64Decode = createDecode(BASE64_CONFIG, base64Validate);
/**
* @name base64Encode
* @summary Creates a base64 value.
* @description
* From the provided input, create the base64 and return the result as a string.
*/
export const base64Encode = createEncode(BASE64_CONFIG);
-18
View File
@@ -1,18 +0,0 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import base64 from 'base64-js';
import { base64Validate } from './validate';
/**
* @name base64Decode
* @summary Decodes a base64 value.
* @description
* From the provided input, decode the base64 and return the result as an `Uint8Array`.
*/
export function base64Decode (value: string): Uint8Array {
base64Validate(value);
return base64.toByteArray(value);
}
-18
View File
@@ -1,18 +0,0 @@
// 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';
/**
* @name base64Encode
* @summary Creates a base64 value.
* @description
* From the provided input, create the base64 and return the result as a string.
*/
export function base64Encode (value: U8aLike): string {
return base64.fromByteArray(u8aToU8a(value));
}
+1 -4
View File
@@ -5,9 +5,6 @@
* @summary Encode and decode base64 values
*/
export { base64Decode } from './decode';
export { base64Encode } from './encode';
export { base64Decode, base64Encode, base64Validate, isBase64 } from './bs64';
export { base64Pad } from './pad';
export { base64Trim } from './trim';
export { base64Validate } from './validate';
export { isBase64 } from './is';
-12
View File
@@ -1,12 +0,0 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { base64Validate } from './validate';
export function isBase64 (value?: string | null): value is string {
try {
return base64Validate(value);
} catch (error) {
return false;
}
}
+4
View File
@@ -1,6 +1,10 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
/**
* @name base64Pad
* @description Adds padding characters for correct length
*/
export function base64Pad (value: string): string {
return value.padEnd(value.length + (value.length % 4), '=');
}
+4
View File
@@ -1,6 +1,10 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
/**
* @name base64Trim
* @description Trims padding characters
*/
export function base64Trim (value: string): string {
while (value.length && value[value.length - 1] === '=') {
value = value.slice(0, -1);
@@ -1,17 +0,0 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { assert } from '@polkadot/util';
/**
* @name base64Validate
* @summary Validates a base64 value.
* @description
* Validates that the supplied value is valid base64
*/
export function base64Validate (value?: string | null): value is string {
assert(value && typeof value === 'string', 'Expected non-null, non-empty base64 string input');
assert(/^(?:[A-Za-z0-9+/]{2}[A-Za-z0-9+/]{2})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value), 'Invalid base64 encoding');
return true;
}
-28
View File
@@ -1,28 +0,0 @@
// 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';
/**
* @name blake2AsHex
* @summary Creates a blake2b hex from the input.
* @description
* From a `Uint8Array` input, create the blake2b and return the result as a hex string with the specified `bitLength`.
* @example
* <BR>
*
* ```javascript
* import { blake2AsHex } from '@polkadot/util-crypto';
*
* blake2AsHex('abc'); // => 0xba80a53f981c4d0d
* ```
*/
export function blake2AsHex (data: HexString | Uint8Array | string, bitLength = 256, key?: Uint8Array | null, onlyJs = false): HexString {
return u8aToHex(
blake2AsU8a(data, bitLength, key, onlyJs)
);
}
@@ -4,6 +4,7 @@
import { hexToU8a } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { performanceTest } from '../../test/performance';
import { blake2AsU8a } from '.';
describe('blake2AsU8a', (): void => {
@@ -58,4 +59,10 @@ describe('blake2AsU8a', (): void => {
expect(a).toEqual(b);
});
describe.each([256, 512] as (256 | 512)[])('bitLength=$p', (bitLength): void => {
performanceTest(`blake2AsU8a, bitLength=${bitLength}`, 64000, (input, onlyJs) =>
blake2AsU8a(input, bitLength, null, onlyJs)
);
});
});
+14 -5
View File
@@ -6,7 +6,9 @@ import type { HexString } from '@polkadot/util/types';
import js from 'blakejs';
import { u8aToU8a } from '@polkadot/util';
import { blake2b, isReady } from '@polkadot/wasm-crypto';
import { blake2b } from '@polkadot/wasm-crypto';
import { createAsHex, isWasmOnly } from '../helpers';
/**
* @name blake2AsU8a
@@ -22,10 +24,17 @@ import { blake2b, isReady } from '@polkadot/wasm-crypto';
* blake2AsU8a('abc'); // => [0xba, 0x80, 0xa5, 0x3f, 0x98, 0x1c, 0x4d, 0x0d]
* ```
*/
export function blake2AsU8a (data: HexString | Uint8Array | string, bitLength = 256, key?: Uint8Array | null, onlyJs = false): Uint8Array {
export function blake2AsU8a (data: HexString | Uint8Array | string, bitLength = 256, key?: Uint8Array | null, onlyJs?: boolean): Uint8Array {
const byteLength = Math.ceil(bitLength / 8);
const u8a = u8aToU8a(data);
return isReady() && !onlyJs
? blake2b(u8aToU8a(data), u8aToU8a(key), byteLength)
: js.blake2b(u8aToU8a(data), key || undefined, byteLength);
return isWasmOnly(onlyJs)
? blake2b(u8a, u8aToU8a(key), byteLength)
: js.blake2b(u8a, key || undefined, byteLength);
}
/**
* @name blake2AsHex
* @description Creates a blake2b hex from the input.
*/
export const blake2AsHex = createAsHex(blake2AsU8a);
+1 -2
View File
@@ -5,5 +5,4 @@
* @summary Create blake2b values with specified bitlengths
*/
export { blake2AsHex } from './asHex';
export { blake2AsU8a } from './asU8a';
export { blake2AsHex, blake2AsU8a } from './asU8a';
+14
View File
@@ -0,0 +1,14 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
export const BN_LE_OPTS = { isLe: true };
export const BN_LE_16_OPTS = { bitLength: 16, isLe: true };
export const BN_BE_32_OPTS = { bitLength: 32, isLe: false };
export const BN_LE_32_OPTS = { bitLength: 32, isLe: true };
export const BN_BE_256_OPTS = { bitLength: 256, isLe: false };
export const BN_LE_256_OPTS = { bitLength: 256, isLe: true };
export const BN_LE_512_OPTS = { bitLength: 512, isLe: true };
+1 -1
View File
@@ -26,6 +26,6 @@ export * from './random';
export * from './schnorrkel';
export * from './scrypt';
export * from './secp256k1';
export * from './sha512';
export * from './sha';
export * from './signature';
export * from './xxhash';
+1 -3
View File
@@ -3,9 +3,7 @@
import { isReady, waitReady } from '@polkadot/wasm-crypto';
export function cryptoIsReady (): boolean {
return isReady();
}
export const cryptoIsReady = isReady;
export function cryptoWaitReady (): Promise<boolean> {
return waitReady()
+2 -2
View File
@@ -29,8 +29,8 @@ export function ethereumEncode (addressOrPublic?: HexString | string | Uint8Arra
const hash = u8aToHex(keccakAsU8a(address), -1, false);
let result = '';
for (let index = 0; index < 40; index++) {
result = `${result}${parseInt(hash[index], 16) > 7 ? address[index].toUpperCase() : address[index]}`;
for (let i = 0; i < 40; i++) {
result = `${result}${parseInt(hash[i], 16) > 7 ? address[i].toUpperCase() : address[i]}`;
}
return `0x${result}`;
@@ -17,8 +17,8 @@ export function isEthereumChecksum (_address: string): boolean {
const address = _address.replace('0x', '');
const hash = u8aToHex(keccakAsU8a(address.toLowerCase()), -1, false);
for (let index = 0; index < 40; index++) {
if (isInvalidChar(address[index], parseInt(hash[index], 16))) {
for (let i = 0; i < 40; i++) {
if (isInvalidChar(address[i], parseInt(hash[i], 16))) {
return false;
}
}
@@ -5,7 +5,8 @@ import type { Keypair } from '../../types';
import { assert, bnToU8a, stringToU8a, u8aConcat } from '@polkadot/util';
import { hmacSha512 } from '../../hmac';
import { BN_BE_32_OPTS } from '../../bn';
import { hmacShaAsU8a } from '../../hmac';
import { secp256k1KeypairFromSeed, secp256k1PrivateKeyTweakAdd } from '../../secp256k1';
import { HARDENED, hdValidatePath } from '../validatePath';
@@ -24,13 +25,13 @@ function createCoded (secretKey: Uint8Array, chainCode: Uint8Array): CodedKeypai
}
function deriveChild (hd: CodedKeypair, index: number): CodedKeypair {
const indexBuffer = bnToU8a(index, { bitLength: 32, isLe: false });
const indexBuffer = bnToU8a(index, BN_BE_32_OPTS);
const data = index >= HARDENED
? u8aConcat(new Uint8Array(1), hd.secretKey, indexBuffer)
: u8aConcat(hd.publicKey, indexBuffer);
try {
const I = hmacSha512(hd.chainCode, data);
const I = hmacShaAsU8a(hd.chainCode, data, 512);
return createCoded(
secp256k1PrivateKeyTweakAdd(hd.secretKey, I.slice(0, 32)),
@@ -43,7 +44,7 @@ function deriveChild (hd: CodedKeypair, index: number): CodedKeypair {
}
export function hdEthereum (seed: Uint8Array, path = ''): Keypair {
const I = hmacSha512(MASTER_SECRET, seed);
const I = hmacShaAsU8a(MASTER_SECRET, seed, 512);
let hd = createCoded(I.slice(0, 32), I.slice(32));
if (!path || path === 'm' || path === 'M' || path === "m'" || path === "M'") {
@@ -3,27 +3,32 @@
import { BN_EIGHT, bnToU8a, u8aConcat, u8aToBn } from '@polkadot/util';
import { hmacSha512 } from '../../hmac';
import { BN_LE_32_OPTS, BN_LE_512_OPTS, BN_LE_OPTS } from '../../bn';
import { hmacShaAsU8a } from '../../hmac';
// performs hard-only derivation on the xprv
export function ledgerDerivePrivate (xprv: Uint8Array, index: number): Uint8Array {
const kl = xprv.subarray(0, 32);
const kr = xprv.subarray(32, 64);
const cc = xprv.subarray(64, 96);
const data = u8aConcat([0], kl, kr, bnToU8a(index, { bitLength: 32, isLe: true }));
const z = hmacSha512(cc, data);
const data = u8aConcat([0], kl, kr, bnToU8a(index, BN_LE_32_OPTS));
const z = hmacShaAsU8a(cc, data, 512);
data[0] = 0x01;
return u8aConcat(
bnToU8a(
u8aToBn(kl, { isLe: true }).iadd(u8aToBn(z.subarray(0, 28), { isLe: true }).imul(BN_EIGHT)),
{ bitLength: 512, isLe: true }
u8aToBn(kl, BN_LE_OPTS).iadd(
u8aToBn(z.subarray(0, 28), BN_LE_OPTS).imul(BN_EIGHT)
),
BN_LE_512_OPTS
).subarray(0, 32),
bnToU8a(
u8aToBn(kr, { isLe: true }).iadd(u8aToBn(z.subarray(32, 64), { isLe: true })),
{ bitLength: 512, isLe: true }
u8aToBn(kr, BN_LE_OPTS).iadd(
u8aToBn(z.subarray(32, 64), BN_LE_OPTS)
),
BN_LE_512_OPTS
).subarray(0, 32),
hmacSha512(cc, data).subarray(32, 64)
hmacShaAsU8a(cc, data, 512).subarray(32, 64)
);
}
+3 -3
View File
@@ -3,7 +3,7 @@
import { u8aConcat } from '@polkadot/util';
import { hmacSha256, hmacSha512 } from '../../hmac';
import { hmacShaAsU8a } from '../../hmac';
import { mnemonicToSeedSync } from '../../mnemonic/bip39';
const ED25519_CRYPTO = 'ed25519 seed';
@@ -11,11 +11,11 @@ const ED25519_CRYPTO = 'ed25519 seed';
// gets an xprv from a mnemonic
export function ledgerMaster (mnemonic: string, password?: string): Uint8Array {
const seed = mnemonicToSeedSync(mnemonic, password);
const chainCode = hmacSha256(ED25519_CRYPTO, new Uint8Array([1, ...seed]));
const chainCode = hmacShaAsU8a(ED25519_CRYPTO, new Uint8Array([1, ...seed]), 256);
let priv;
while (!priv || (priv[31] & 0b0010_0000)) {
priv = hmacSha512(ED25519_CRYPTO, priv || seed);
priv = hmacShaAsU8a(ED25519_CRYPTO, priv || seed, 512);
}
priv[0] &= 0b1111_1000;
+22
View File
@@ -0,0 +1,22 @@
// 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 { isReady } from '@polkadot/wasm-crypto';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function createAsHex <T extends (...args: any[]) => Uint8Array> (fn: T): (...args: Parameters<T>) => HexString {
return (...args: Parameters<T>): HexString =>
u8aToHex(fn(...args));
}
export function createBitHasher <T> (bitLength: T, fn: (data: HexString | Buffer | Uint8Array | string, bitLength: T, onlyJs?: boolean) => Uint8Array): (data: HexString | Buffer | Uint8Array | string, onlyJs?: boolean) => Uint8Array {
return (data: HexString | Buffer | Uint8Array | string, onlyJs?: boolean): Uint8Array =>
fn(data, bitLength, onlyJs);
}
export function isWasmOnly (onlyJs?: boolean): boolean {
return isReady() && !onlyJs;
}
+1 -2
View File
@@ -1,5 +1,4 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
export { hmacSha256 } from './sha256';
export { hmacSha512 } from './sha512';
export { hmacShaAsU8a, hmacSha256AsU8a, hmacSha512AsU8a } from './shaAsU8a';
-14
View File
@@ -1,14 +0,0 @@
// 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());
}
-8
View File
@@ -1,8 +0,0 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { hmacSha } from './sha';
export function hmacSha256 (key: Uint8Array | string, data: Uint8Array): Uint8Array {
return hmacSha(key, data, false);
}
-8
View File
@@ -1,8 +0,0 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { hmacSha } from './sha';
export function hmacSha512 (key: Uint8Array | string, data: Uint8Array): Uint8Array {
return hmacSha(key, data, true);
}
@@ -0,0 +1,39 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { hexToU8a, stringToU8a } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { performanceTest } from '../../test/performance';
import { hmacShaAsU8a } from '.';
describe('hmacShaAsU8a', (): void => {
beforeEach(async (): Promise<void> => {
await waitReady();
});
const key = stringToU8a('secret');
const data = stringToU8a('some message');
const output = {
256: hexToU8a(
'0xf28a70b41263840e5c059a0a733336e0957efba87902aa8cca11441d4b0c96d7'
),
512: hexToU8a(
'0x295832e97ed77be75a9fa98029497e4a722c4b9a2f21b39d34f1befa931a39ec520fd24711d6f5c03501384ea66b83066a01a82c57a0460f8cd1f471fcce5841'
)
};
describe.each([256, 512] as (256 | 512)[])('bitLength=$p', (bitLength): void => {
describe.each([false, true])('onlyJs=%p', (onlyJs): void => {
it('returns an hex representation (string)', (): void => {
expect(
hmacShaAsU8a(key, data, bitLength, onlyJs)
).toEqual(output[bitLength]);
});
});
performanceTest(`hmacShaAsU8a, bitLength=${bitLength}`, 16000, (input, onlyJs) =>
hmacShaAsU8a(input, input, bitLength, onlyJs)
);
});
});
+38
View File
@@ -0,0 +1,38 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import hash from 'hash.js';
import { u8aToU8a } from '@polkadot/util';
import { hmacSha256, hmacSha512 } from '@polkadot/wasm-crypto';
import { isWasmOnly } from '../helpers';
type HashFn = (key: Uint8Array | string, data: Uint8Array, onlyJs?: boolean) => Uint8Array;
function createSha (bitLength: 256 | 512 = 256): HashFn {
return (key: Uint8Array | string, data: Uint8Array, onlyJs?: boolean): Uint8Array =>
hmacShaAsU8a(key, data, bitLength, onlyJs);
}
export function hmacShaAsU8a (key: Uint8Array | string, data: Uint8Array, bitLength: 256 | 512 = 256, onlyJs?: boolean): Uint8Array {
const is256 = bitLength === 256;
const u8aKey = u8aToU8a(key);
return isWasmOnly(onlyJs)
? is256
? hmacSha256(u8aKey, data)
: hmacSha512(u8aKey, data)
: new Uint8Array(
is256
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
? hash.hmac(hash.sha256, u8aKey).update(data).digest()
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
: hash.hmac(hash.sha512, u8aKey).update(data).digest()
);
}
export const hmacSha256AsU8a = createSha(256);
export const hmacSha512AsU8a = createSha(512);
-28
View File
@@ -1,28 +0,0 @@
// 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';
/**
* @name keccakAsHex
* @summary Creates a keccak hex string from the input.
* @description
* From either a `string` or a `Buffer` input, create the keccak and return the result as a `0x` prefixed hex string.
* @example
* <BR>
*
* ```javascript
* import { keccakAsHex } from '@polkadot/util-crypto';
*
* keccakAsHex('123'); // => 0x...
* ```
*/
export function keccakAsHex (value: HexString | Buffer | Uint8Array | string, bitLength?: 256 | 512): HexString {
return u8aToHex(
keccakAsU8a(value, bitLength)
);
}
@@ -4,6 +4,7 @@
import { hexToU8a, stringToU8a } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { performanceTest } from '../../test/performance';
import { keccakAsU8a } from '.';
describe('keccakAsU8a', (): void => {
@@ -21,8 +22,8 @@ describe('keccakAsU8a', (): void => {
)
};
describe.each([false, true])('onlyJs=%p', (onlyJs): void => {
describe.each([256, 512] as (256 | 512)[])('bitLength=$p', (bitLength): void => {
describe.each([256, 512] as (256 | 512)[])('bitLength=$p', (bitLength): void => {
describe.each([false, true])('onlyJs=%p', (onlyJs): void => {
it('returns an hex representation (string)', (): void => {
expect(
keccakAsU8a(input, bitLength, onlyJs)
@@ -41,5 +42,9 @@ describe('keccakAsU8a', (): void => {
).toEqual(output[bitLength]);
});
});
performanceTest(`keccakAsU8a, bitLength=${bitLength}`, 128000, (input, onlyJs) =>
keccakAsU8a(input, bitLength, onlyJs)
);
});
});
+30 -5
View File
@@ -6,7 +6,9 @@ import type { HexString } from '@polkadot/util/types';
import js from 'js-sha3';
import { u8aToU8a } from '@polkadot/util';
import { isReady, keccak256 } from '@polkadot/wasm-crypto';
import { keccak256, keccak512 } from '@polkadot/wasm-crypto';
import { createAsHex, createBitHasher, isWasmOnly } from '../helpers';
/**
* @name keccakAsU8a
@@ -22,12 +24,35 @@ import { isReady, keccak256 } from '@polkadot/wasm-crypto';
* keccakAsU8a('123'); // => Uint8Array
* ```
*/
export function keccakAsU8a (value: HexString | Buffer | Uint8Array | string, bitLength: 256 | 512 = 256, onlyJs = false): Uint8Array {
export function keccakAsU8a (value: HexString | Buffer | Uint8Array | string, bitLength: 256 | 512 = 256, onlyJs?: boolean): Uint8Array {
const is256 = bitLength === 256;
const u8a = u8aToU8a(value);
return isReady() && is256 && !onlyJs
? keccak256(u8aToU8a(value))
return isWasmOnly(onlyJs)
? is256
? keccak256(u8a)
: keccak512(u8a)
: new Uint8Array(
(is256 ? js.keccak256 : js.keccak512).update(u8aToU8a(value)).arrayBuffer()
is256
? js.keccak256.update(u8a).arrayBuffer()
: js.keccak512.update(u8a).arrayBuffer()
);
}
/**
* @name keccak256AsU8a
* @description Creates a keccak256 Uint8Array from the input.
*/
export const keccak256AsU8a = createBitHasher(256, keccakAsU8a);
/**
* @name keccak512AsU8a
* @description Creates a keccak512 Uint8Array from the input.
*/
export const keccak512AsU8a = createBitHasher(512, keccakAsU8a);
/**
* @name keccakAsHex
* @description Creates a keccak hex string from the input.
*/
export const keccakAsHex = createAsHex(keccakAsU8a);
+1 -2
View File
@@ -5,5 +5,4 @@
* @summary Create Keccak256/512 values as hex & Uint8Array output
*/
export { keccakAsHex } from './asHex';
export { keccakAsU8a } from './asU8a';
export { keccakAsHex, keccakAsU8a, keccak256AsU8a, keccak512AsU8a } from './asU8a';
@@ -6,14 +6,11 @@ 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';
import { BN_LE_256_OPTS } from '../bn';
const RE_NUMBER = /^\d+$/;
const JUNCTION_ID_LEN = 32;
const BN_OPTIONS = {
bitLength: 256,
isLe: true
};
export class DeriveJunction {
readonly #chainCode: Uint8Array = new Uint8Array(32);
@@ -61,7 +58,7 @@ export class DeriveJunction {
public soft (value: HexString | number | string | bigint | BN | Uint8Array): DeriveJunction {
if (isNumber(value) || isBn(value) || isBigInt(value)) {
return this.soft(bnToU8a(value, BN_OPTIONS));
return this.soft(bnToU8a(value, BN_LE_256_OPTS));
} else if (isHex(value)) {
return this.soft(hexToU8a(value));
} else if (isString(value)) {
File diff suppressed because one or more lines are too long
+9 -12
View File
@@ -13,12 +13,11 @@
// - Remove setting of wordlist passing of wordlist in functions
// - Remove mnemonicToSeed (we only use the sync variant)
import hash from 'hash.js';
import { assert, stringToU8a, u8aToU8a } from '@polkadot/util';
import { pbkdf2Encode } from '../pbkdf2';
import { randomAsU8a } from '../random/asU8a';
import { randomAsU8a } from '../random';
import { sha256AsU8a } from '../sha';
import DEFAULT_WORDLIST from './bip39-en';
const INVALID_MNEMONIC = 'Invalid mnemonic';
@@ -38,18 +37,16 @@ function bytesToBinary (bytes: number[]): string {
}
function deriveChecksumBits (entropyBuffer: Uint8Array): string {
const ENT = entropyBuffer.length * 8;
const CS = ENT / 32;
const result = hash.sha256().update(entropyBuffer).digest();
return bytesToBinary(Array.from(result)).slice(0, CS);
return bytesToBinary(
Array.from(sha256AsU8a(entropyBuffer))
).slice(0, (entropyBuffer.length * 8) / 32);
}
export function mnemonicToSeedSync (mnemonic: string, password?: string): Uint8Array {
const mnemonicBuffer = stringToU8a(normalize(mnemonic));
const saltBuffer = stringToU8a(`mnemonic${normalize(password)}`);
return pbkdf2Encode(mnemonicBuffer, saltBuffer).password;
return pbkdf2Encode(
stringToU8a(normalize(mnemonic)),
stringToU8a(`mnemonic${normalize(password)}`)
).password;
}
export function mnemonicToEntropy (mnemonic: string): Uint8Array {
@@ -1,8 +1,9 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { bip39Generate, isReady } from '@polkadot/wasm-crypto';
import { bip39Generate } from '@polkadot/wasm-crypto';
import { isWasmOnly } from '../helpers';
import { generateMnemonic } from './bip39';
export type WordCount = 12 | 15 | 18 | 21 | 24;
@@ -28,8 +29,8 @@ const STRENGTH_MAP = {
* const mnemonic = mnemonicGenerate(); // => string
* ```
*/
export function mnemonicGenerate (numWords: WordCount = 12, onlyJs = false): string {
return isReady() && !onlyJs
export function mnemonicGenerate (numWords: WordCount = 12, onlyJs?: boolean): string {
return isWasmOnly(onlyJs)
? bip39Generate(numWords)
: generateMnemonic(STRENGTH_MAP[numWords]);
}
@@ -1,12 +1,13 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { bip39ToEntropy, isReady } from '@polkadot/wasm-crypto';
import { bip39ToEntropy } from '@polkadot/wasm-crypto';
import { isWasmOnly } from '../helpers';
import { mnemonicToEntropy as jsToEntropy } from './bip39';
export function mnemonicToEntropy (mnemonic: string, onlyJs = false): Uint8Array {
return isReady() && !onlyJs
export function mnemonicToEntropy (mnemonic: string, onlyJs?: boolean): Uint8Array {
return isWasmOnly(onlyJs)
? bip39ToEntropy(mnemonic)
: jsToEntropy(mnemonic);
}
@@ -2,8 +2,9 @@
// SPDX-License-Identifier: Apache-2.0
import { assert } from '@polkadot/util';
import { bip39ToSeed, isReady } from '@polkadot/wasm-crypto';
import { bip39ToSeed } from '@polkadot/wasm-crypto';
import { isWasmOnly } from '../helpers';
import { mnemonicToSeedSync } from './bip39';
import { mnemonicValidate } from './validate';
@@ -24,12 +25,12 @@ import { mnemonicValidate } from './validate';
* }
* ```
*/
export function mnemonicToLegacySeed (mnemonic: string, password = '', onlyJs = false, byteLength: 32 | 64 = 32): Uint8Array {
export function mnemonicToLegacySeed (mnemonic: string, password = '', onlyJs?: boolean, byteLength: 32 | 64 = 32): Uint8Array {
assert(mnemonicValidate(mnemonic), 'Invalid bip39 mnemonic specified');
assert([32, 64].includes(byteLength), () => `Invalid seed length ${byteLength}, expected 32 or 64`);
if (byteLength === 32) {
return isReady() && !onlyJs
return isWasmOnly(onlyJs)
? bip39ToSeed(mnemonic, password)
: mnemonicToSeedSync(mnemonic, password).subarray(0, 32);
} else if (byteLength === 64) {
@@ -2,16 +2,17 @@
// SPDX-License-Identifier: Apache-2.0
import { assert, stringToU8a } from '@polkadot/util';
import { bip39ToMiniSecret, isReady } from '@polkadot/wasm-crypto';
import { bip39ToMiniSecret } from '@polkadot/wasm-crypto';
import { isWasmOnly } from '../helpers';
import { pbkdf2Encode } from '../pbkdf2';
import { mnemonicToEntropy } from './toEntropy';
import { mnemonicValidate } from './validate';
export function mnemonicToMiniSecret (mnemonic: string, password = '', onlyJs = false): Uint8Array {
export function mnemonicToMiniSecret (mnemonic: string, password = '', onlyJs?: boolean): Uint8Array {
assert(mnemonicValidate(mnemonic), 'Invalid bip39 mnemonic specified');
if (isReady() && !onlyJs) {
if (isWasmOnly(onlyJs)) {
return bip39ToMiniSecret(mnemonic, password);
}
@@ -1,8 +1,9 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { bip39Validate, isReady } from '@polkadot/wasm-crypto';
import { bip39Validate } from '@polkadot/wasm-crypto';
import { isWasmOnly } from '../helpers';
import { validateMnemonic } from './bip39';
/**
@@ -18,8 +19,8 @@ import { validateMnemonic } from './bip39';
* const isValidMnemonic = mnemonicValidate(mnemonic); // => boolean
* ```
*/
export function mnemonicValidate (mnemonic: string, onlyJs = false): boolean {
return isReady() && !onlyJs
export function mnemonicValidate (mnemonic: string, onlyJs?: boolean): boolean {
return isWasmOnly(onlyJs)
? bip39Validate(mnemonic)
: validateMnemonic(mnemonic);
}
@@ -0,0 +1,36 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { u8aToHex } from '@polkadot/util';
import { convertPublicKeyToCurve25519, convertSecretKeyToCurve25519 } from '.';
describe('convertPublicKeyToCurve25519', (): void => {
it('converts a known key correctly', (): void => {
expect(
u8aToHex(convertPublicKeyToCurve25519(
new Uint8Array([
180, 114, 93, 155, 165, 255, 217, 82,
16, 250, 209, 11, 193, 10, 88, 218,
190, 190, 41, 193, 236, 252, 1, 152,
216, 214, 0, 41, 45, 138, 13, 53
])
))
).toEqual('0x5e05848ceeef4f306d6e285a26faf1a8070cf0c89f8d28ab966002fe4ad17746');
});
});
describe('convertSecretKeyToCurve25519', (): void => {
it('converts a known key correctly', (): void => {
expect(
u8aToHex(convertSecretKeyToCurve25519(
new Uint8Array([
1, 2, 3, 4, 5, 6, 7, 8,
1, 2, 3, 4, 5, 6, 7, 8,
1, 2, 3, 4, 5, 6, 7, 8,
1, 2, 3, 4, 5, 6, 7, 8
])
))
).toEqual('0xd875a82940b9174dabb1c0c895485810cc2870f5808565b59d4ef708bdcf526c');
});
});
+3 -1
View File
@@ -3,10 +3,12 @@
import ed2curve from 'ed2curve';
import { assertReturn } from '@polkadot/util';
export function convertSecretKeyToCurve25519 (secretKey: Uint8Array): Uint8Array {
return ed2curve.convertSecretKey(secretKey);
}
export function convertPublicKeyToCurve25519 (publicKey: Uint8Array): Uint8Array {
return ed2curve.convertPublicKey(publicKey) as Uint8Array;
return assertReturn(ed2curve.convertPublicKey(publicKey), 'Unable to convert publicKey to ed25519');
}
@@ -21,7 +21,7 @@ import { ed25519KeypairFromSeed, isReady } from '@polkadot/wasm-crypto';
* naclKeypairFromSeed(...); // => { secretKey: [...], publicKey: [...] }
* ```
*/
export function naclKeypairFromSeed (seed: Uint8Array, onlyJs = false): Keypair {
export function naclKeypairFromSeed (seed: Uint8Array, onlyJs?: boolean): Keypair {
if (!onlyJs && isReady()) {
const full = ed25519KeypairFromSeed(seed);
+13 -11
View File
@@ -32,19 +32,19 @@ describe('naclOpen', (): void => {
// Receiver sends encrypting public key to receive message to decrypt with his private key
const receiverIdBoxKey = naclBoxKeypairFromSecret(receiverIdKey.secretKey);
console.log(`Receiver sends receiver's public key to sender ${receiverIdBoxKey.publicKey.toString()}`);
// console.log(`Receiver sends receiver's public key to sender ${receiverIdBoxKey.publicKey.toString()}`);
// Sender encrypts message to send with the public key the receiver sent and send it to receiver
const senderIdBoxKey = naclBoxKeypairFromSecret(senderIdKey.secretKey);
const message = new Uint8Array([1, 2, 3, 4, 5, 4, 3, 2, 1]);
const { nonce, sealed } = naclSeal(message, senderIdBoxKey.secretKey, receiverIdBoxKey.publicKey);
console.log(`Sender sends encrypted message to receiver ${sealed.toString()}, ${nonce.toString()}`);
// console.log(`Sender sends encrypted message to receiver ${sealed.toString()}, ${nonce.toString()}`);
// Receiver opens encrypted message from the sender
let opened = naclOpen(sealed, nonce, senderIdBoxKey.publicKey, receiverIdBoxKey.secretKey);
console.log(`The sealed message is ${opened?.toString() || 'null'}`);
// console.log(`The sealed message is ${opened?.toString() || 'null'}`);
// Oh no the Id key is hacked, derive Id key again from another index
const senderIdKey2 = keyFromPath(sender, keyExtractPath('//1//1//1//2').path, 'ed25519');
@@ -53,7 +53,7 @@ describe('naclOpen', (): void => {
// Receiver sends encrypting public key to receive message to decrypt with his private key
const receiverIdBoxKey2 = naclBoxKeypairFromSecret(receiverIdKey2.secretKey);
console.log(`Receiver sends receiver's public key to sender ${receiverIdBoxKey2.publicKey.toString()}`);
// console.log(`Receiver sends receiver's public key to sender ${receiverIdBoxKey2.publicKey.toString()}`);
// Sender encrypts message to send with the public key the receiver sent and send it to receiver
const senderIdBoxKey2 = naclBoxKeypairFromSecret(senderIdKey2.secretKey);
@@ -62,17 +62,17 @@ describe('naclOpen', (): void => {
const sealed2 = ctx.sealed;
const nonce2 = ctx.nonce;
console.log(`Sender sends encrypted message to receiver ${sealed.toString()}, ${nonce.toString()}`);
// console.log(`Sender sends encrypted message to receiver ${sealed.toString()}, ${nonce.toString()}`);
// Receiver opens encrypted message from the sender
opened = naclOpen(sealed2, nonce2, senderIdBoxKey2.publicKey, receiverIdBoxKey2.secretKey);
console.log(`The sealed message is ${opened?.toString() || 'null'}`);
// console.log(`The sealed message is ${opened?.toString() || 'null'}`);
// This time derive key for each message to send and receive
// Receiver sends encrypting public key to receive message to decrypt with his private key
const receiverIdBoxKey2One = naclBoxKeypairFromSecret(receiverIdBoxKey2.secretKey);
console.log(`Receiver sends receiver's public key to sender ${receiverIdBoxKey2One.publicKey.toString()}`);
// console.log(`Receiver sends receiver's public key to sender ${receiverIdBoxKey2One.publicKey.toString()}`);
// Sender encrypts message to send with the public key the receiver sent and send it to receiver
const senderIdBoxKey2One = naclBoxKeypairFromSecret(senderIdBoxKey2.secretKey);
@@ -80,14 +80,16 @@ describe('naclOpen', (): void => {
ctx = naclSeal(message3, senderIdBoxKey2One.secretKey, receiverIdBoxKey2One.publicKey);
const sealed3 = ctx.sealed;
const nonce3 = ctx.nonce;
// const sealed3 = ctx.sealed;
// const nonce3 = ctx.nonce;
console.log(`Sender sends encrypted message to receiver ${sealed3.toString()}, ${nonce3.toString()}`);
// console.log(`Sender sends encrypted message to receiver ${sealed3.toString()}, ${nonce3.toString()}`);
// Receiver opens encrypted message from the sender
opened = naclOpen(sealed2, nonce2, senderIdBoxKey2One.publicKey, receiverIdBoxKey2One.secretKey);
console.log(`The sealed message is ${opened?.toString() || 'null'}`);
expect(opened).toEqual(message3);
// console.log(`The sealed message is ${opened?.toString() || 'null'}`);
});
it('returns null on invalid', (): void => {
+10 -3
View File
@@ -4,8 +4,13 @@
import { stringToU8a } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { performanceTest } from '../../test/performance';
import { naclKeypairFromSeed, naclSign } from '.';
const PAIR = naclKeypairFromSeed(
stringToU8a('12345678901234567890123456789012')
);
describe('naclSign', (): void => {
beforeEach(async (): Promise<void> => {
await waitReady();
@@ -16,9 +21,7 @@ describe('naclSign', (): void => {
expect(
naclSign(
new Uint8Array([0x61, 0x62, 0x63, 0x64]),
naclKeypairFromSeed(
stringToU8a('12345678901234567890123456789012')
),
PAIR,
onlyJs
)
).toEqual(
@@ -26,4 +29,8 @@ describe('naclSign', (): void => {
);
});
});
performanceTest('naclSign', 250, (input, onlyJs) =>
naclSign(input, PAIR, onlyJs)
);
});
+5 -3
View File
@@ -7,7 +7,9 @@ import type { Keypair } from '../types';
import nacl from 'tweetnacl';
import { assert, u8aToU8a } from '@polkadot/util';
import { ed25519Sign, isReady } from '@polkadot/wasm-crypto';
import { ed25519Sign } from '@polkadot/wasm-crypto';
import { isWasmOnly } from '../helpers';
/**
* @name naclSign
@@ -23,12 +25,12 @@ import { ed25519Sign, isReady } from '@polkadot/wasm-crypto';
* naclSign([...], [...]); // => [...]
* ```
*/
export function naclSign (message: HexString | Uint8Array | string, { publicKey, secretKey }: Partial<Keypair>, onlyJs = false): Uint8Array {
export function naclSign (message: HexString | Uint8Array | string, { publicKey, secretKey }: Partial<Keypair>, onlyJs?: boolean): Uint8Array {
assert(secretKey, 'Expected a valid secretKey');
const messageU8a = u8aToU8a(message);
return isReady() && !onlyJs
return isWasmOnly(onlyJs)
? ed25519Sign(publicKey as Uint8Array, secretKey.subarray(0, 32), messageU8a)
: nacl.sign.detached(messageU8a, secretKey);
}
+5 -3
View File
@@ -6,7 +6,9 @@ import type { HexString } from '@polkadot/util/types';
import nacl from 'tweetnacl';
import { assert, u8aToU8a } from '@polkadot/util';
import { ed25519Verify, isReady } from '@polkadot/wasm-crypto';
import { ed25519Verify } from '@polkadot/wasm-crypto';
import { isWasmOnly } from '../helpers';
/**
* @name naclSign
@@ -22,7 +24,7 @@ import { ed25519Verify, isReady } from '@polkadot/wasm-crypto';
* naclVerify([...], [...], [...]); // => true/false
* ```
*/
export function naclVerify (message: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, publicKey: HexString | Uint8Array | string, onlyJs = false): boolean {
export function naclVerify (message: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, publicKey: HexString | Uint8Array | string, onlyJs?: boolean): boolean {
const messageU8a = u8aToU8a(message);
const publicKeyU8a = u8aToU8a(publicKey);
const signatureU8a = u8aToU8a(signature);
@@ -30,7 +32,7 @@ export function naclVerify (message: HexString | Uint8Array | string, signature:
assert(publicKeyU8a.length === 32, () => `Invalid publicKey, received ${publicKeyU8a.length}, expected 32`);
assert(signatureU8a.length === 64, () => `Invalid signature, received ${signatureU8a.length} bytes, expected 64`);
return isReady() && !onlyJs
return isWasmOnly(onlyJs)
? ed25519Verify(signatureU8a, messageU8a, publicKeyU8a)
: nacl.sign.detached.verify(messageU8a, signatureU8a, publicKeyU8a);
}
+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.8.2' };
export const packageInfo = { name: '@polkadot/util-crypto', version: '7.9.2' };
@@ -7,7 +7,12 @@ import { waitReady } from '@polkadot/wasm-crypto';
import { randomAsU8a } from '../random/asU8a';
import { pbkdf2Encode } from '.';
const KNOWN_SALT = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]);
const KNOWN_SALT = new Uint8Array([
1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32
]);
const TEST_PASSWORD = 'test password';
describe('pbkdf2Encode', (): void => {
+10 -6
View File
@@ -4,8 +4,9 @@
import type { HexString } from '@polkadot/util/types';
import { u8aToU8a } from '@polkadot/util';
import { isReady, pbkdf2 } from '@polkadot/wasm-crypto';
import { pbkdf2 } from '@polkadot/wasm-crypto';
import { isWasmOnly } from '../helpers';
import { randomAsU8a } from '../random/asU8a';
import { pbkdf2Sync } from './pbkdf2';
@@ -15,12 +16,15 @@ interface Result {
salt: Uint8Array;
}
export function pbkdf2Encode (passphrase?: HexString | 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?: boolean): Result {
const u8aPass = u8aToU8a(passphrase);
const u8aSalt = u8aToU8a(salt);
const password = isReady() && !onlyJs
? pbkdf2(u8aPass, u8aSalt, rounds)
: pbkdf2Sync(u8aPass, u8aSalt, rounds);
return { password, rounds, salt };
return {
password: isWasmOnly(onlyJs)
? pbkdf2(u8aPass, u8aSalt, rounds)
: pbkdf2Sync(u8aPass, u8aSalt, rounds),
rounds,
salt
};
}
+5 -4
View File
@@ -5,7 +5,8 @@
import { bnToU8a, u8aConcat } from '@polkadot/util';
import { hmacSha512 } from '../hmac';
import { BN_BE_32_OPTS } from '../bn';
import { hmacShaAsU8a } from '../hmac';
export function pbkdf2Sync (password: Uint8Array, salt: Uint8Array, rounds: number, len = 64): Uint8Array {
let out = new Uint8Array();
@@ -14,14 +15,14 @@ export function pbkdf2Sync (password: Uint8Array, salt: Uint8Array, rounds: numb
while (out.length < len) {
num++;
block.set(bnToU8a(num, { bitLength: 32, isLe: false }), salt.length);
block.set(bnToU8a(num, BN_BE_32_OPTS), salt.length);
let prev = hmacSha512(password, block);
let prev = hmacShaAsU8a(password, block, 512);
const md = prev;
let i = 0;
while (++i < rounds) {
prev = hmacSha512(password, prev);
prev = hmacShaAsU8a(password, prev, 512);
let j = -1;
-28
View File
@@ -1,28 +0,0 @@
// 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';
/**
* @name randomAsHex
* @summary Creates a hex string filled with random bytes.
* @description
* Returns a hex string with the specified (optional) length filled with random bytes.
* @example
* <BR>
*
* ```javascript
* import { randomAsHex } from '@polkadot/util-crypto';
*
* randomAsHex(); // => 0x...
* ```
*/
export function randomAsHex (length = 32): HexString {
return u8aToHex(
randomAsU8a(length)
);
}
+1 -1
View File
@@ -3,7 +3,7 @@
import { BN, hexToBn } from '@polkadot/util';
import { randomAsHex } from './asHex';
import { randomAsHex } from './asU8a';
const BN_53 = new BN(0b11111111111111111111111111111111111111111111111111111);
+8
View File
@@ -3,6 +3,8 @@
import { getRandomValues } from '@polkadot/x-randomvalues';
import { createAsHex } from '../helpers';
/**
* @name randomAsU8a
* @summary Creates a Uint8Array filled with random bytes.
@@ -20,3 +22,9 @@ import { getRandomValues } from '@polkadot/x-randomvalues';
export function randomAsU8a (length = 32): Uint8Array {
return getRandomValues(new Uint8Array(length));
}
/**
* @name randomAsHex
* @description Creates a hex string filled with random bytes.
*/
export const randomAsHex = createAsHex(randomAsU8a);
+1 -2
View File
@@ -5,6 +5,5 @@
* @summary Returns a sequence of secure random bytes in a variety of formats
*/
export { randomAsHex } from './asHex';
export { randomAsNumber } from './asNumber';
export { randomAsU8a } from './asU8a';
export { randomAsHex, randomAsU8a } from './asU8a';
@@ -0,0 +1,36 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { waitReady } from '@polkadot/wasm-crypto';
import { performanceTest } from '../../test/performance';
import { DEFAULT_PARAMS } from './defaults';
import { scryptEncode } from '.';
export const KNOWN_TEST = 'testing, 123';
export const KNOWN_PASS = new Uint8Array([223, 185, 241, 135, 125, 17, 195, 27, 64, 64, 154, 69, 47, 82, 123, 38, 255, 230, 199, 200, 101, 115, 21, 116, 119, 59, 67, 43, 58, 220, 112, 70, 124, 139, 240, 206, 42, 148, 140, 132, 64, 226, 164, 25, 104, 80, 49, 92, 144, 132, 109, 178, 76, 225, 171, 116, 151, 181, 34, 243, 177, 235, 134, 76]);
export const KNOWN_SALT = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8]);
describe('scryptEncode', (): void => {
beforeEach(async (): Promise<void> => {
await waitReady();
});
describe.each([false, true])('onlyJs=%p', (onlyJs): void => {
it('generates a known output', (): void => {
expect(
scryptEncode(KNOWN_TEST, KNOWN_SALT, undefined, onlyJs)
).toEqual({
params: DEFAULT_PARAMS,
password: KNOWN_PASS,
salt: KNOWN_SALT
});
});
});
performanceTest('scryptEncode', 2, (input, onlyJs) =>
scryptEncode(input, input, undefined, onlyJs)
);
});

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