Compare commits

..
53 Commits
Author SHA1 Message Date
Github Actions e2fa0ad11f [CI Skip] release/stable 5.6.1
skip-checks: true
2021-02-07 11:20:47 +00:00
Jaco Greeff 654e44aa99 5.6 (#874)
* 5.6

* bnSqrt opt

* Additional sqrt tests

* Adjust bnSqrt input types

* test-case attributions
2021-02-07 12:14:55 +01:00
Github Actions 476689f615 [CI Skip] release/beta 5.5.3-4
skip-checks: true
2021-02-07 08:58:19 +00:00
Raoul Millais fc1582aa70 Fix yarn add instructions in x-global README (#873) 2021-02-07 09:52:42 +01:00
Github Actions a616b84045 [CI Skip] release/beta 5.5.3-3
skip-checks: true
2021-02-06 16:10:42 +00:00
Jaco Greeff 73708b72c7 Allow double-byte ss58 (#868)
* Allow double-byte ss58

* Update keyring tests (non-68)

* Range check

* Fixup tests and encoding

* Adjust keyring test

* Adjust

* Assert format

* Additionl subkey equivalency tests

* ecdsa tests

* Remove invalid test

* UpdateAssert of reserved

* Cleanups

* cleanups

* Last test for Substrate equality

* crosscheck update

* network null

* network
2021-02-06 17:05:54 +01:00
Github Actions 8f0807ddbe [CI Skip] release/beta 5.5.3-2
skip-checks: true
2021-02-06 15:51:45 +00:00
Jaco Greeff 5547f885be ss58 alignment 2021-02-06 16:46:18 +01:00
Github Actions 5f8d521c6a [CI Skip] release/beta 5.5.3-1
skip-checks: true
2021-02-04 10:31:52 +00:00
Jaco Greeff 51a169a88a Tests for vrf{Sign, Verify} (#870) 2021-02-04 11:26:19 +01:00
Github Actions ad89ed5f3d [CI Skip] release/beta 5.5.3-0
skip-checks: true
2021-02-04 07:56:15 +00:00
Jaco Greeff ca1362c595 Cleanup Buffer.from usages, expand tests (#869)
* Cleanup Bffer.from usages, expand tests

* validate mnemonic tests & cleanups
2021-02-04 08:50:07 +01:00
Github Actions 9621d90613 [CI Skip] release/stable 5.5.2
skip-checks: true
2021-02-02 14:46:59 +00:00
Jaco Greeff 50efeb06d1 5.5.2 (#867) 2021-02-02 15:41:25 +01:00
Github Actions e236acc29d [CI Skip] release/beta 5.5.2-1
skip-checks: true
2021-02-02 14:26:05 +00:00
Jaco Greeff 1062ace58d BN_{MILLION, BILLION} (#866)
* BN_{MILLION, BILLION}

* Add BN(2-9)

* adjust

* inline

* BN_TWO

* BN_ZERO

* BN_ONE gets used in return
2021-02-02 15:20:31 +01:00
Github Actions 298a901921 [CI Skip] release/beta 5.5.2-0
skip-checks: true
2021-02-01 13:45:17 +00:00
Jaco Greeff c2f453481c Additional hdLedger tests (#863) 2021-02-01 14:39:14 +01:00
Github Actions 54e6b61972 [CI Skip] release/stable 5.5.1
skip-checks: true
2021-01-31 07:57:36 +00:00
Jaco Greeff c52a7b1e64 5.5 (#862)
* 5.5

* Remove extra arg from mnemonicToLegacySeed
2021-01-31 08:51:43 +01:00
Github Actions 749cd2e381 [CI Skip] release/beta 5.4.5-1
skip-checks: true
2021-01-30 19:07:49 +00:00
Jaco Greeff 24b1790c99 Add hmac{Sha256, 512} (#861)
* Add hmac{Sha256, 512}

* Adjust

* private hmac
2021-01-30 20:02:21 +01:00
Github Actions 62823635b0 [CI Skip] release/beta 5.4.5-0
skip-checks: true
2021-01-30 17:38:17 +00:00
Jaco Greeff bc84220108 Add Ledger-compatible derivation (#860)
* Add Ledger-compatible derivation

* Export hd from root

* Renames
2021-01-30 18:33:15 +01:00
Jaco Greeff 5158951326 Give bot permissions to post issues 2021-01-26 16:36:49 +01:00
Github Actions 500b739ddd [CI Skip] release/stable 5.4.4
skip-checks: true
2021-01-24 15:44:51 +00:00
Jaco Greeff b741d228ac Use xglobal everywhere 2021-01-24 16:40:04 +01:00
Jaco Greeff 437ff8b51d Use x-gobal in node polyfills 2021-01-24 16:39:22 +01:00
Github Actions 354dd0a7a4 [CI Skip] release/stable 5.4.3
skip-checks: true
2021-01-24 15:03:21 +00:00
Jaco Greeff 3804123ca6 Remove browser.ts global reference (#856)
* Remove browser.ts global reference

* fallback text

* formatting

* Additional formatting

* global > self > window > this

* Add x-global package

* Update tests

* Correct jest mapping
2021-01-24 15:58:42 +01:00
Github Actions bbc752e475 [CI Skip] release/stable 5.4.2
skip-checks: true
2021-01-24 11:13:49 +00:00
Jaco Greeff 80f69b88b2 5.4.2 (#855) 2021-01-24 12:09:14 +01:00
Github Actions a02eab478e [CI Skip] release/stable 5.4.1
skip-checks: true
2021-01-24 07:58:18 +00:00
Jaco Greeff 22fdb9a1f9 5.4 (#854) 2021-01-24 08:53:32 +01:00
Github Actions 496d2123ed [CI Skip] release/beta 5.3.2-8
skip-checks: true
2021-01-23 08:38:47 +00:00
Jaco Greeff 15a2e6c6cf Allow formatBalance to take array defaults (#853) 2021-01-23 09:34:04 +01:00
Github Actions 62a9a7aeb5 [CI Skip] release/beta 5.3.2-7
skip-checks: true
2021-01-22 09:34:00 +00:00
Jaco Greeff 8541088893 Bump wasm (#851) 2021-01-22 10:28:34 +01:00
Github Actions e558cf8f7f [CI Skip] release/beta 5.3.2-6
skip-checks: true
2021-01-21 19:30:31 +00:00
Jaco Greeff 01827deaf5 EDCSA derive test (#850) 2021-01-21 20:24:48 +01:00
Github Actions 6d71677c17 [CI Skip] release/beta 5.3.2-5
skip-checks: true
2021-01-21 12:35:26 +00:00
Jaco Greeff ee42a717aa Bump wasm (#848) 2021-01-21 13:30:39 +01:00
Github Actions cfa8ab7ab6 [CI Skip] release/beta 5.3.2-4
skip-checks: true
2021-01-21 10:39:31 +00:00
Adam DossaandAdam Dossa 4ecd14c187 Update ledger key to polymesh (from polymath) (#847)
Co-authored-by: Adam Dossa <adamdossa@Adams-MacBook-Pro.local>
2021-01-21 11:34:17 +01:00
Github Actions d9318bc917 [CI Skip] release/beta 5.3.2-3
skip-checks: true
2021-01-20 13:17:28 +00:00
Jaco Greeff 6f6db63580 Add vrf{Sign, Verify} to kering interface (#846) 2021-01-20 14:11:50 +01:00
Github Actions ebd1e64694 [CI Skip] release/beta 5.3.2-2
skip-checks: true
2021-01-20 11:59:45 +00:00
Jaco Greeff f12aa92383 Add schnorrkelVrf{Sign, Verify} functions (#845)
* Add schnorrkelVrf{Sign, Verify} functions

* Apply suggestions from code review
2021-01-20 12:54:59 +01:00
Github Actions 2df0638b19 [CI Skip] release/beta 5.3.2-1
skip-checks: true
2021-01-19 20:36:18 +00:00
Jaco Greeff 542f484703 Move x-rxjs from @polkadot/api (#844)
* Move x-rxjs from @polkadot/api

* yarn

* x-rxjs bump

* jest config
2021-01-19 21:30:42 +01:00
Github Actions f9dbedb93a [CI Skip] release/beta 5.3.2-0
skip-checks: true
2021-01-19 20:16:43 +00:00
Jaco Greeff 2492ae5d60 Update ss58 (#843) 2021-01-19 21:11:05 +01:00
Jaco Greeff c5ab1c0e1a Update CHANGELOG.md 2021-01-17 15:57:20 +01:00
90 changed files with 2601 additions and 1195 deletions
+5
View File
@@ -3,3 +3,8 @@
2.12.2
5.2.2
5.2.3
5.4.2
5.4.3
5.4.4
5.5.2
+1 -1
View File
@@ -19,6 +19,6 @@ jobs:
if: ${{ failure() }}
uses: JasonEtco/create-an-issue@v2
env:
GITHUB_TOKEN: ${{ secrets.GH_PAT }}
GITHUB_TOKEN: ${{ secrets.GH_PAT_BOT }}
with:
filename: .github/ss58-check.md
+52
View File
@@ -1,11 +1,63 @@
# CHANGELOG
## 5.6.1 Feb 7, 2021
Contributed:
- Fix installation instructions in `@polkadot/x-global` (Thanks to https://github.com/raoulmillais)
Changes:
- Conform to new ss58 encoding with ids up to 16,383 (>= 64 as 2 bytes)
- Use JS sqrt inside `bnSqrt` when value <= MAX_SAFE_INTEGER
- Adjust all `Buffer.from` usages, prefer `Uint8Array` where possible
- Expand tests for keyring with `vrf{Sign, Verify}`
- Align `@polkadot/networks` with latest ss58 registry
## 5.5.2 Feb 2, 2021
Changes:
- Expose `BN_{MILLION, BILLION}` constants (in addition to 2-9)
## 5.5.1 Jan 31, 2021
Changes:
- Added `hdLedger` to util-crypto for Ledger-compatible bip32+ed25519 derivation
- Added `hmac{Sha256, 512}` to util-crypto
- Add `slip44` indices for Ledger into `@polkadot/networks`
- Remove `module` entry in `package.json` (only rely on exports map)
- Remove direct references to `global` object, use `@polkadot/x-global`
- Update `@ledgerhq` dependencies to latest
## 5.4.1 Jan 24, 2021
Contributed:
- Adjust Ledger app lookup for Polymesh (Thanks to https://github.com/adamdossa)
Changes:
- Allow decimals as `number[]` & symbol as `string[]` in balanceFormat defaults
- Add `schnorrkelVrf{Sign, Verify}` to `@polkadot/util-crypto`
- Export `vrf{Sign, Verify}` on keyring interface
- Move `@polkadot/x-rxjs` packages from the api repo
- Align `@polkadot/networks` with Substrate master
- Explicit edcsa tests for derivation
- `@polkadot/wasm-crypto` 3.2.1
## 5.3.1 Jan 17, 2021
**Important** For users of the `@polkadot/ledger` package, it is now included in this repo (since it is a general utility) and renamed to `@polkadot/hw-ledger`
Contributed:
- Add Dock Ledger integration (Thanks to https://github.com/lovesh)
- Add Polymesh Ledger integration (Thanks to https://github.com/adamdossa)
- Add flag for Ledger capabilities on networks (Thanks to https://github.com/Tbaut)
+5 -1
View File
@@ -13,7 +13,9 @@ module.exports = Object.assign({}, config, {
'@polkadot/util-(crypto)(.*)$': '<rootDir>/packages/util-$1/src/$2',
// eslint-disable-next-line sort-keys
'@polkadot/util(.*)$': '<rootDir>/packages/util/src/$1',
'@polkadot/x-(fetch|randomvalues|textdecoder|textencoder|ws)(.*)$': '<rootDir>/packages/x-$1/src/node'
'@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',
@@ -23,7 +25,9 @@ module.exports = Object.assign({}, config, {
'<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'
+3 -3
View File
@@ -20,10 +20,10 @@
"test:one": "polkadot-dev-run-test"
},
"devDependencies": {
"@babel/core": "^7.12.10",
"@polkadot/dev": "^0.61.24",
"@babel/core": "^7.12.13",
"@polkadot/dev": "^0.61.25",
"@polkadot/ts": "^0.3.59",
"@types/jest": "^26.0.20"
},
"version": "5.3.1"
"version": "5.6.1"
}
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/hw-ledger-transports",
"version": "5.3.1",
"version": "5.6.1",
"repository": "github:polkadot-js/common",
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
@@ -11,14 +11,14 @@
"react-native": "react-native.js",
"sideEffects": false,
"dependencies": {
"@babel/runtime": "^7.12.5",
"@ledgerhq/hw-transport-webusb": "^5.39.0"
"@babel/runtime": "^7.12.13",
"@ledgerhq/hw-transport-webusb": "^5.41.0"
},
"devDependencies": {
"@types/ledgerhq__hw-transport-node-hid": "^4.22.2",
"@types/ledgerhq__hw-transport-webusb": "^4.70.1"
},
"optionalDependencies": {
"@ledgerhq/hw-transport-node-hid-singleton": "^5.39.0"
"@ledgerhq/hw-transport-node-hid-singleton": "^5.41.0"
}
}
+4 -5
View File
@@ -1,18 +1,17 @@
{
"name": "@polkadot/hw-ledger",
"version": "5.3.1",
"version": "5.6.1",
"repository": "github:polkadot-js/common",
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
"contributors": [],
"license": "Apache-2.0",
"main": "index.js",
"module": "index.mjs",
"sideEffects": false,
"dependencies": {
"@babel/runtime": "^7.12.5",
"@polkadot/hw-ledger-transports": "5.3.1",
"@polkadot/util": "^5.3.1",
"@babel/runtime": "^7.12.13",
"@polkadot/hw-ledger-transports": "5.6.1",
"@polkadot/util": "^5.6.1",
"@zondax/ledger-polkadot": "^0.13.0"
}
}
+1 -1
View File
@@ -24,7 +24,7 @@ const APPS: Record<string, (transport: Transport) => SubstrateApp> = {
dock: newDockApp,
kusama: newKusamaApp,
polkadot: newPolkadotApp,
polymath: newPolymeshApp
polymesh: newPolymeshApp
};
type Chain = keyof typeof APPS;
+6 -7
View File
@@ -1,13 +1,12 @@
{
"name": "@polkadot/keyring",
"version": "5.3.1",
"version": "5.6.1",
"description": "Keyring management",
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
"contributors": [],
"license": "Apache-2.0",
"main": "index.js",
"module": "index.mjs",
"sideEffects": [
"./detectPackage.js",
"./detectPackage.mjs"
@@ -16,12 +15,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.12.5",
"@polkadot/util": "5.3.1",
"@polkadot/util-crypto": "5.3.1"
"@babel/runtime": "^7.12.13",
"@polkadot/util": "5.6.1",
"@polkadot/util-crypto": "5.6.1"
},
"peerDependencies": {
"@polkadot/util": "5.3.1",
"@polkadot/util-crypto": "5.3.1"
"@polkadot/util": "5.6.1",
"@polkadot/util-crypto": "5.6.1"
}
}
+6 -6
View File
@@ -46,11 +46,11 @@ describe('keypair', (): void => {
it('adds from a mnemonic, with correct ss58', (): void => {
setSS58Format(20); // this would not be used
keyring.setSS58Format(68); // this would be used
keyring.setSS58Format(2); // this would be used
const pair = keyring.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {});
expect(pair.address).toEqual('7sPsxWPE5DzAyPT3VuoJYw5NTGscx9QYN9oddQx4kALKC3hH');
expect(pair.address).toEqual('HSLu2eci2GCfWkRimjjdTXKoFSDL3rBv5Ey2JWCBj68cVZj');
expect(encodeAddress(pair.publicKey)).toEqual('35cDYtPsdG1HUa2n2MaARgJyRz1WKMBZK1DL6c5cX7nugQh1');
});
@@ -123,11 +123,11 @@ describe('keypair', (): void => {
});
it('adds from a mnemonic', (): void => {
keyring.setSS58Format(68);
keyring.setSS58Format(2);
expect(
keyring.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {}).address
).toEqual('7qQGarA4PWjPPVHG4USn1yuuVZvEHN7XZz8o7EbAp48jayZQ');
).toEqual('FSjXNRT2K1R5caeHLPD6WMrqYUpfGZB7ua8W89JFctZ1YqV');
});
it('allows publicKeys retrieval', (): void => {
@@ -200,11 +200,11 @@ describe('keypair', (): void => {
});
it('adds from a mnemonic', (): void => {
keyring.setSS58Format(68);
keyring.setSS58Format(2);
expect(
keyring.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card').address
).toEqual('7ooxHV3mz4nnWbK8v7Mxcb71QMpof268eL1A2VrYWUNWJk8P');
).toEqual('DrRE1KAcs4pCicX8yJPh7YxkLPQ2vXnCFSVRPQfx38KjEFe');
});
it('allows publicKeys retrieval', (): void => {
+14 -7
View File
@@ -56,6 +56,17 @@ describe('pair', (): void => {
).toEqual(false);
});
it('allows vrf sign and verify', (): void => {
const message = new Uint8Array([0x61, 0x62, 0x63, 0x64, 0x65]);
expect(
keyring.alice.vrfVerify(
message,
keyring.alice.vrfSign(message)
)
).toBe(true);
});
it('allows setting/getting of meta', (): void => {
keyring.bob.setMeta({ foo: 'bar', something: 'else' });
@@ -67,15 +78,11 @@ describe('pair', (): void => {
});
it('allows encoding of address with different prefixes', (): void => {
expect(keyring.alice.address).toEqual(
'5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua'
);
expect(keyring.alice.address).toEqual('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua');
setSS58Format(68);
setSS58Format(255);
expect(keyring.alice.address).toEqual(
'7sGUeMak588SPY2YMmmuKUuLz7u2WQpf74F9dCFtSLB2td9d'
);
expect(keyring.alice.address).toEqual('yGHU8YKprxHbHdEv7oUK4rzMZXtsdhcXVG2CAMyC9WhzhjH2k');
setSS58Format(42);
});
+34 -13
View File
@@ -5,8 +5,8 @@ import type { Keypair, KeypairType } from '@polkadot/util-crypto/types';
import type { KeyringPair, KeyringPair$Json, KeyringPair$JsonEncodingTypes, KeyringPair$Meta, SignOptions } from '../types';
import type { PairInfo } from './types';
import { assert, u8aConcat, u8aToHex } from '@polkadot/util';
import { blake2AsU8a, ethereumEncode, keccakAsU8a, keyExtractPath, keyFromPath, naclKeypairFromSeed as naclFromSeed, naclSign, schnorrkelKeypairFromSeed as schnorrkelFromSeed, schnorrkelSign, secp256k1Compress, secp256k1Expand, secp256k1KeypairFromSeed as secp256k1FromSeed, secp256k1Sign, signatureVerify } from '@polkadot/util-crypto';
import { assert, u8aConcat, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util';
import { blake2AsU8a, ethereumEncode, keccakAsU8a, keyExtractPath, keyFromPath, naclKeypairFromSeed as naclFromSeed, naclSign, schnorrkelKeypairFromSeed as schnorrkelFromSeed, schnorrkelSign, schnorrkelVrfSign, schnorrkelVrfVerify, secp256k1Compress, secp256k1Expand, secp256k1KeypairFromSeed as secp256k1FromSeed, secp256k1Sign, signatureVerify } from '@polkadot/util-crypto';
import { decodePair } from './decode';
import { encodePair } from './encode';
@@ -47,13 +47,13 @@ const TYPE_ADDRESS = {
sr25519: (p: Uint8Array) => p
};
function isEmpty (u8a: Uint8Array): boolean {
return u8a.reduce((count, u8) => count + u8, 0) === 0;
}
// Not 100% correct, since it can be a Uint8Array, but an invalid one - just say "undefined" is anything non-valid
function isLocked (secretKey?: Uint8Array): secretKey is undefined {
return !secretKey || secretKey.length === 0 || isEmpty(secretKey);
return !secretKey || secretKey.length === 0 || secretKey.every((b) => b === 0);
}
function vrfHash (proof: Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): Uint8Array {
return blake2AsU8a(u8aConcat(context || '', extra || '', proof));
}
/**
@@ -152,22 +152,23 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
return createPair({ toSS58, type }, derived, meta, null);
},
encodePkcs8: (passphrase?: string): Uint8Array =>
recode(passphrase),
encodePkcs8: (passphrase?: string): Uint8Array => {
return recode(passphrase);
},
lock: (): void => {
secretKey = new Uint8Array();
},
setMeta: (additional: KeyringPair$Meta): void => {
meta = { ...meta, ...additional };
},
sign: (message: Uint8Array, options: SignOptions = {}): Uint8Array => {
sign: (message: string | Uint8Array, options: SignOptions = {}): Uint8Array => {
assert(!isLocked(secretKey), 'Cannot sign with a locked key pair');
return u8aConcat(
options.withType
? TYPE_PREFIX[type]
: SIG_TYPE_NONE,
TYPE_SIGNATURE[type](message, { publicKey, secretKey })
TYPE_SIGNATURE[type](u8aToU8a(message), { publicKey, secretKey })
);
},
toJson: (passphrase?: string): KeyringPair$Json => {
@@ -177,7 +178,27 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
return pairToJson(type, { address, meta }, recode(passphrase), !!passphrase);
},
verify: (message: Uint8Array, signature: Uint8Array): boolean =>
signatureVerify(message, signature, TYPE_ADDRESS[type](publicKey)).isValid
verify: (message: string | Uint8Array, signature: Uint8Array): boolean => {
return signatureVerify(message, signature, TYPE_ADDRESS[type](publicKey)).isValid;
},
vrfSign: (message: string | Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): Uint8Array => {
assert(!isLocked(secretKey), 'Cannot sign with a locked key pair');
if (type === 'sr25519') {
return schnorrkelVrfSign(message, { secretKey }, context, extra);
}
const proof = TYPE_SIGNATURE[type](u8aToU8a(message), { publicKey, secretKey });
return u8aConcat(vrfHash(proof, context, extra), proof);
},
vrfVerify: (message: string | Uint8Array, vrfResult: Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): boolean => {
return type === 'sr25519'
? schnorrkelVrfVerify(message, vrfResult, publicKey, context, extra)
: (
signatureVerify(message, u8aConcat(TYPE_PREFIX[type], vrfResult.subarray(32)), TYPE_ADDRESS[type](publicKey)).isValid &&
u8aEq(vrfResult.subarray(0, 32), vrfHash(vrfResult.subarray(32), context, extra))
);
}
};
}
+6
View File
@@ -53,6 +53,12 @@ export function nobody (): KeyringPair {
type: 'ed25519',
// 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
};
+53
View File
@@ -0,0 +1,53 @@
// Copyright 2017-2021 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { KeyringPair } from '../types';
import { u8aToHex } from '@polkadot/util';
import { cryptoWaitReady, encodeAddress as toSS58, naclKeypairFromSeed, randomAsU8a, schnorrkelKeypairFromSeed, secp256k1KeypairFromSeed } from '@polkadot/util-crypto';
import { createPair } from '.';
const MESSAGE = 'this is a test message';
const CONTEXT = 'some context';
describe('vrf', (): void => {
let ecdsa: KeyringPair;
let ed25519: KeyringPair;
let sr25519: KeyringPair;
beforeAll(async (): Promise<void> => {
await cryptoWaitReady();
ecdsa = createPair({ toSS58, type: 'ecdsa' }, secp256k1KeypairFromSeed(randomAsU8a()));
ed25519 = createPair({ toSS58, type: 'ed25519' }, naclKeypairFromSeed(randomAsU8a()));
sr25519 = createPair({ toSS58, type: 'sr25519' }, schnorrkelKeypairFromSeed(randomAsU8a()));
});
it('has deterministic signature values for ecdsa', (): void => {
const sig1 = ecdsa.vrfSign(MESSAGE, CONTEXT);
const sig2 = ecdsa.vrfSign(MESSAGE, CONTEXT);
expect(u8aToHex(sig1)).toEqual(u8aToHex(sig2));
expect(ecdsa.vrfVerify(MESSAGE, sig1, CONTEXT)).toEqual(true);
expect(ecdsa.vrfVerify(MESSAGE, sig2, CONTEXT)).toEqual(true);
});
it('has deterministic signature values for ed25519', (): void => {
const sig1 = ed25519.vrfSign(MESSAGE, CONTEXT);
const sig2 = ed25519.vrfSign(MESSAGE, CONTEXT);
expect(u8aToHex(sig1)).toEqual(u8aToHex(sig2));
expect(ed25519.vrfVerify(MESSAGE, sig1, CONTEXT)).toEqual(true);
expect(ed25519.vrfVerify(MESSAGE, sig2, CONTEXT)).toEqual(true);
});
it('has deterministic signature values for sr25519', (): void => {
const sig1 = sr25519.vrfSign(MESSAGE, CONTEXT);
const sig2 = sr25519.vrfSign(MESSAGE, CONTEXT);
expect(u8aToHex(sig1.slice(0, 32))).toEqual(u8aToHex(sig2.slice(0, 32)));
expect(sr25519.vrfVerify(MESSAGE, sig1, CONTEXT)).toEqual(true);
expect(sr25519.vrfVerify(MESSAGE, sig2, CONTEXT)).toEqual(true);
});
});
+65 -52
View File
@@ -10,53 +10,62 @@ import Keyring from '.';
const PHRASE = 'bottom drive obey lake curtain smoke basket hold race lonely fit walk';
const TESTS = [
{
pk: '0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a',
ss: '5DfhGyQdFobKM8NsWvEeAKk5EQQgYe9AydgJ7rMB6E1EqRzV',
uri: PHRASE
},
{
pk: '0xb69355deefa7a8f33e9297f5af22e680f03597a99d4f4b1c44be47e7a2275802',
ss: '5GC6LfpV352HtJPySfAecb5JdePtf4R9Vq49NUU8RhzgBqgq',
uri: `${PHRASE}///password`
},
{
pk: '0x40b9675df90efa6069ff623b0fdfcf706cd47ca7452a5056c7ad58194d23440a',
ss: '5DXZzrDxHbkQov4QBAY4TjpwnHCMrKXkomTnKSw8UArBEY5v',
uri: `${PHRASE}/foo`
},
{
pk: '0x547d4a55642ec7ebadc0bd29b6e570b8c926059b3c0655d4948075e9a7e6f31e',
ss: '5DyV6fZuvPemWrUqBgWwTSgoV86w6xms3KhkFU6cQcWxU8eP',
uri: `${PHRASE}//foo`
},
{
pk: '0x3841947ffcde6f5fef26fb68b59bb8665637e30e32ec2051f99cf6b9c674fe09',
ss: '5DLU27is5iViNopQb2KxsTyPx6j4vCu8X3sk3j3NNLkPCqKM',
uri: `${PHRASE}//foo/bar`
},
{
pk: '0xdc142f7476a7b0aa262aeccf207f1d18daa90762db393006741e8a31f39dbc53',
ss: '5H3GPTqDSpjkfDwbHy12PD6BWm8jvGSX4xYC8UMprHpTPcRg',
uri: `${PHRASE}/foo//bar`
},
{
pk: '0xa2e56b06407a6d1e819d2fc33fa0ec604b29c2e868b70b3696bb049b8725934b',
ss: '5FkHmNgbg64MwStgCyDi2Uw3ufFu11mqQgmWT9uwK4Lghvpv',
uri: `${PHRASE}//foo/bar//42/69`
},
{
pk: '0x0e0d24e3e1ff2c07f269c99e2e0df8681fda1851ac42fc846ca2daaa90cd8f14',
ss: '5CP8S23JBNXYNpJsL7ESPJBNnUZE6itcfM4EnDxEhaVEU6dT',
uri: `${PHRASE}//foo/bar//42/69///password`
},
{
pk: '0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d',
ss: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
uri: `${PHRASE}//Alice`
}
];
const TESTS = {
ecdsa: [
{
pk: '0x020a1091341fe5664bfa1782d5e04779689068c916b04cb365ec3153755684d9a1',
ss: '5C7C2Z5sWbytvHpuLTvzKunnnRwQxft1jiqrLD5rhucQ5S9X',
uri: `${PHRASE}//Alice`
}
],
sr25519: [
{
pk: '0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a',
ss: '5DfhGyQdFobKM8NsWvEeAKk5EQQgYe9AydgJ7rMB6E1EqRzV',
uri: PHRASE
},
{
pk: '0xb69355deefa7a8f33e9297f5af22e680f03597a99d4f4b1c44be47e7a2275802',
ss: '5GC6LfpV352HtJPySfAecb5JdePtf4R9Vq49NUU8RhzgBqgq',
uri: `${PHRASE}///password`
},
{
pk: '0x40b9675df90efa6069ff623b0fdfcf706cd47ca7452a5056c7ad58194d23440a',
ss: '5DXZzrDxHbkQov4QBAY4TjpwnHCMrKXkomTnKSw8UArBEY5v',
uri: `${PHRASE}/foo`
},
{
pk: '0x547d4a55642ec7ebadc0bd29b6e570b8c926059b3c0655d4948075e9a7e6f31e',
ss: '5DyV6fZuvPemWrUqBgWwTSgoV86w6xms3KhkFU6cQcWxU8eP',
uri: `${PHRASE}//foo`
},
{
pk: '0x3841947ffcde6f5fef26fb68b59bb8665637e30e32ec2051f99cf6b9c674fe09',
ss: '5DLU27is5iViNopQb2KxsTyPx6j4vCu8X3sk3j3NNLkPCqKM',
uri: `${PHRASE}//foo/bar`
},
{
pk: '0xdc142f7476a7b0aa262aeccf207f1d18daa90762db393006741e8a31f39dbc53',
ss: '5H3GPTqDSpjkfDwbHy12PD6BWm8jvGSX4xYC8UMprHpTPcRg',
uri: `${PHRASE}/foo//bar`
},
{
pk: '0xa2e56b06407a6d1e819d2fc33fa0ec604b29c2e868b70b3696bb049b8725934b',
ss: '5FkHmNgbg64MwStgCyDi2Uw3ufFu11mqQgmWT9uwK4Lghvpv',
uri: `${PHRASE}//foo/bar//42/69`
},
{
pk: '0x0e0d24e3e1ff2c07f269c99e2e0df8681fda1851ac42fc846ca2daaa90cd8f14',
ss: '5CP8S23JBNXYNpJsL7ESPJBNnUZE6itcfM4EnDxEhaVEU6dT',
uri: `${PHRASE}//foo/bar//42/69///password`
},
{
pk: '0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d',
ss: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
uri: `${PHRASE}//Alice`
}
]
};
describe('keyring.addFromUri', (): void => {
const keyring = new Keyring({ type: 'sr25519' });
@@ -65,12 +74,16 @@ describe('keyring.addFromUri', (): void => {
await cryptoWaitReady();
});
TESTS.forEach(({ pk, ss, uri }): void => {
it(`creates ${uri}`, (): void => {
const pair = keyring.addFromUri(uri);
Object.entries(TESTS).forEach(([type, tests]): void => {
describe(type, (): void => {
tests.forEach(({ pk, ss, uri }): void => {
it(`creates ${uri}`, (): void => {
const pair = keyring.addFromUri(uri, {}, type as 'sr25519');
expect(u8aToHex(pair.publicKey)).toEqual(pk);
expect(pair.address).toEqual(ss);
expect(u8aToHex(pair.publicKey)).toEqual(pk);
expect(pair.address).toEqual(ss);
});
});
});
});
});
+4 -2
View File
@@ -45,9 +45,11 @@ export interface KeyringPair {
encodePkcs8: (passphrase?: string) => Uint8Array;
lock: () => void;
setMeta: (meta: KeyringPair$Meta) => void;
sign (message: Uint8Array, options?: SignOptions): Uint8Array;
sign (message: string | Uint8Array, options?: SignOptions): Uint8Array;
toJson (passphrase?: string): KeyringPair$Json;
verify (message: Uint8Array, signature: Uint8Array): boolean;
verify (message: string | Uint8Array, signature: Uint8Array): boolean;
vrfSign (message: string | Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): Uint8Array;
vrfVerify (message: string | Uint8Array, vrfResult: Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): boolean;
}
export interface KeyringPairs {
+4 -5
View File
@@ -1,9 +1,8 @@
{
"name": "@polkadot/networks",
"version": "5.3.1",
"version": "5.6.1",
"description": "A list of all available Substrate networks and their applicable prefixes",
"main": "index.js",
"module": "index.mjs",
"sideEffects": false,
"repository": "github:polkadot-js/common",
"author": "Jaco Greeff <jacogr@gmail.com>",
@@ -13,10 +12,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.12.5"
"@babel/runtime": "^7.12.13"
},
"devDependencies": {
"@polkadot/util": "5.3.1",
"@polkadot/x-fetch": "5.3.1"
"@polkadot/util": "5.6.1",
"@polkadot/x-fetch": "5.6.1"
}
}
+29 -17
View File
@@ -16,11 +16,11 @@ const UNSORTED = [0, 2, 42];
// last. This make lookups for the current a simple genesisHash[0]
// (See Kusama as an example)
const createReserved = (prefix: number, displayName = 'This prefix is reserved.'): NetworkFromSubstrate => ({
const createReserved = (prefix: number, displayName: string, network: string | null = null): NetworkFromSubstrate => ({
decimals: null,
displayName,
isIgnored: true,
network: `reserved${prefix}`,
network,
prefix,
standardAccount: null,
symbols: null,
@@ -36,11 +36,12 @@ const all: NetworkFromSubstrate[] = [
icon: 'polkadot',
network: 'polkadot',
prefix: 0,
slip44: 0x00000162,
standardAccount: '*25519',
symbols: ['DOT'],
website: 'https://polkadot.network'
},
createReserved(1),
createReserved(1, 'Bare 32-bit Schnorr/Ristretto (S/R 25519) public key.'),
{
decimals: [12],
displayName: 'Kusama Relay Chain',
@@ -53,11 +54,12 @@ const all: NetworkFromSubstrate[] = [
icon: 'polkadot',
network: 'kusama',
prefix: 2,
slip44: 0x000001b2,
standardAccount: '*25519',
symbols: ['KSM'],
website: 'https://kusama.network'
},
createReserved(3),
createReserved(3, 'Bare 32-bit Ed25519 public key.'),
{
decimals: null,
displayName: 'Katal Chain',
@@ -133,15 +135,16 @@ const all: NetworkFromSubstrate[] = [
website: 'http://laminar.network/'
},
{
decimals: null,
displayName: 'Polymath',
decimals: [6],
displayName: 'Polymesh',
genesisHash: ['0x12fddc9e2128b3fe571e4e5427addcb87fcaf08493867a68dd6ae44b406b39c7'],
hasLedgerSupport: true,
network: 'polymath',
network: 'polymesh',
prefix: 12,
slip44: 0x00000253,
standardAccount: '*25519',
symbols: null,
website: null
symbols: ['POLYX'],
website: 'https://polymath.network/'
},
{
decimals: null,
@@ -234,6 +237,7 @@ const all: NetworkFromSubstrate[] = [
hasLedgerSupport: true,
network: 'dock-mainnet',
prefix: 22,
slip44: 0x00000252,
standardAccount: '*25519',
symbols: ['DCK'],
website: 'https://dock.io'
@@ -314,13 +318,22 @@ const all: NetworkFromSubstrate[] = [
website: 'https://phala.network'
},
{
decimals: null,
displayName: 'Robonomics Network',
decimals: [12],
displayName: 'Litentry Network',
network: 'litentry',
prefix: 31,
standardAccount: '*25519',
symbols: ['LIT'],
website: 'https://litentry.com/'
},
{
decimals: [9],
displayName: 'Robonomics',
network: 'robonomics',
prefix: 32,
standardAccount: '*25519',
symbols: null,
website: null
symbols: ['XRT'],
website: 'https://robonomics.network'
},
{
decimals: null,
@@ -404,7 +417,7 @@ const all: NetworkFromSubstrate[] = [
symbols: null,
website: 'https://substrate.dev/'
},
createReserved(43),
createReserved(43, 'Bare 32-bit ECDSA SECP-256k1 public key.'),
{
decimals: [8],
displayName: 'ChainX',
@@ -423,9 +436,8 @@ const all: NetworkFromSubstrate[] = [
symbols: ['UART', 'UINK'],
website: 'https://uniarts.me'
},
createReserved(46),
createReserved(47),
createReserved(48, 'All prefixes 48 and higher are reserved and cannot be allocated.')
createReserved(46, 'This prefix is reserved.', 'reserved46'),
createReserved(47, 'This prefix is reserved.', 'reserved47')
];
// The list of available/claimed prefixes
+2 -1
View File
@@ -6,12 +6,13 @@ export type Icon = 'beachball' | 'empty' | 'jdenticon' | 'polkadot' | 'substrate
export interface NetworkFromSubstrate {
decimals: number[] | null,
displayName: string;
network: string;
network: string | null;
prefix: number;
genesisHash?: string[] | null;
hasLedgerSupport?: boolean;
icon?: Icon | null;
isIgnored?: boolean;
slip44?: number;
standardAccount: '*25519' | null;
symbols: string[] | null;
website: string | null;
+8 -9
View File
@@ -1,9 +1,8 @@
{
"name": "@polkadot/util-crypto",
"version": "5.3.1",
"version": "5.6.1",
"description": "A collection of useful crypto utilities for @polkadot",
"main": "index.js",
"module": "index.mjs",
"sideEffects": [
"./detectPackage.js",
"./detectPackage.mjs"
@@ -16,16 +15,16 @@
"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.12.5",
"@polkadot/networks": "5.3.1",
"@polkadot/util": "5.3.1",
"@polkadot/wasm-crypto": "^3.1.1",
"@polkadot/x-randomvalues": "5.3.1",
"@babel/runtime": "^7.12.13",
"@polkadot/networks": "5.6.1",
"@polkadot/util": "5.6.1",
"@polkadot/wasm-crypto": "^3.2.2",
"@polkadot/x-randomvalues": "5.6.1",
"base-x": "^3.0.8",
"blakejs": "^1.1.0",
"bn.js": "^4.11.9",
"create-hash": "^1.2.0",
"elliptic": "^6.5.3",
"elliptic": "^6.5.4",
"hash.js": "^1.1.7",
"js-sha3": "^0.8.0",
"scryptsy": "^2.1.0",
@@ -40,6 +39,6 @@
"@types/xxhashjs": "^0.2.2"
},
"peerDependencies": {
"@polkadot/util": "5.3.1"
"@polkadot/util": "5.6.1"
}
}
+4 -4
View File
@@ -22,13 +22,13 @@ export function checkAddress (address: string, prefix: Prefix): [boolean, string
return [false, (error as Error).message];
}
if (decoded[0] !== prefix) {
return [false, `Prefix mismatch, expected ${prefix}, found ${decoded[0]}`];
const [isValid,,, ss58Decoded] = checkAddressChecksum(decoded);
if (ss58Decoded !== prefix) {
return [false, `Prefix mismatch, expected ${prefix}, found ${ss58Decoded}`];
} else if (!defaults.allowedEncodedLengths.includes(decoded.length)) {
return [false, 'Invalid decoded address length'];
}
const [isValid] = checkAddressChecksum(decoded);
return [isValid, isValid ? null : 'Invalid decoded address checksum'];
}
@@ -0,0 +1,25 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { base58Decode } from '../base58/decode';
import { checkAddressChecksum } from './checksum';
describe('checkAddressChecksum', (): void => {
it('correctly extracts the info from a 1-byte-prefix address', (): void => {
expect(
checkAddressChecksum(base58Decode('F3opxRbN5ZbjJNU511Kj2TLuzFcDq9BGduA9TgiECafpg29'))
).toEqual([true, 33, 1, 2]);
});
it('correctly extracts the info from a 2-byte-prefix address', (): void => {
expect(
checkAddressChecksum(base58Decode('yGHU8YKprxHbHdEv7oUK4rzMZXtsdhcXVG2CAMyC9WhzhjH2k'))
).toEqual([true, 34, 2, 255]);
});
it('correctly extracts the info from a 2-byte-prefix address (ecdsa, from Substrate)', (): void => {
expect(
checkAddressChecksum(base58Decode('4pbsSkWcBaYoFHrKJZp5fDVUKbqSYD9dhZZGvpp3vQ5ysVs5ybV'))
).toEqual([true, 35, 2, 200]);
});
});
+13 -9
View File
@@ -3,19 +3,23 @@
import { sshash } from './sshash';
export function checkAddressChecksum (decoded: Uint8Array): [boolean, number] {
const isPublicKey = [35, 36].includes(decoded.length);
export function checkAddressChecksum (decoded: Uint8Array): [boolean, number, number, number] {
const ss58Length = (decoded[0] & 0b0100_0000) ? 2 : 1;
const ss58Decoded = ss58Length === 1
? decoded[0]
: ((decoded[0] & 0b0011_1111) << 2) | (decoded[1] >> 6) | ((decoded[1] & 0b0011_1111) << 8);
// non-publicKeys has 1 byte checksums, else default to 2
// 32/33 bytes public + 2 bytes checksum + prefix
const isPublicKey = [34 + ss58Length, 35 + ss58Length].includes(decoded.length);
const length = decoded.length - (isPublicKey ? 2 : 1);
// calculate the hash and do the checksum byte checks
const hash = sshash(decoded.subarray(0, length));
const isValid = (decoded[0] & 0b1000_0000) === 0 && ![46, 47].includes(decoded[0]) && (
isPublicKey
? decoded[decoded.length - 2] === hash[0] && decoded[decoded.length - 1] === hash[1]
: decoded[decoded.length - 1] === hash[0]
);
// see if the hash actually matches
const isValid = isPublicKey
? decoded[decoded.length - 2] === hash[0] && decoded[decoded.length - 1] === hash[1]
: decoded[decoded.length - 1] === hash[0];
return [isValid, length];
return [isValid, length, ss58Length, ss58Decoded];
}
@@ -51,25 +51,25 @@ describe('decodeAddress', (): void => {
it('decodes a 1-byte accountId (with prefix)', (): void => {
expect(
decodeAddress('PqtB', false, 68)
decodeAddress('g4b', false, 2)
).toEqual(new Uint8Array([1]));
});
it('decodes a 2-byte accountId', (): void => {
expect(
decodeAddress('2jpAFn', false, 68)
decodeAddress('3xygo', false, 2)
).toEqual(new Uint8Array([0, 1]));
});
it('encodes a 4-byte address', (): void => {
expect(
decodeAddress('as7QnGMf', false, 68)
decodeAddress('zswfoZa', false, 2)
).toEqual(new Uint8Array([1, 2, 3, 4]));
});
it('decodes a 8-byte address', (): void => {
expect(
decodeAddress('4q7qY5RBG7Z4wv', false, 68)
decodeAddress('848Gh2GcGaZia', false, 2)
).toEqual(new Uint8Array([42, 44, 10, 0, 0, 0, 0, 0]));
});
@@ -81,6 +81,20 @@ describe('decodeAddress', (): void => {
);
});
it('decodes a 2-byte prefix', (): void => {
expect(
decodeAddress('yGHU8YKprxHbHdEv7oUK4rzMZXtsdhcXVG2CAMyC9WhzhjH2k')
).toEqual(
decodeAddress('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua')
);
});
it('decodes a 2-byte prefix (ecdsa, from Substrate)', (): void => {
expect(
u8aToHex(decodeAddress('4pbsSkWcBaYoFHrKJZp5fDVUKbqSYD9dhZZGvpp3vQ5ysVs5ybV'))
).toEqual('0x035676109c54b9a16d271abeb4954316a40a32bcce023ac14c8e26e958aa68fba9');
});
it.skip('allows invalid prefix (in list)', (): void => {
expect(
(): Uint8Array => decodeAddress('6GfvWUvHvU8otbZ7sFhXH4eYeMcKdUkL61P3nFy52efEPVUx')
+11 -20
View File
@@ -10,32 +10,23 @@ import { base58Decode } from '../base58/decode';
import { checkAddressChecksum } from './checksum';
import { defaults } from './defaults';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function decodeAddress (encoded: string | Uint8Array, ignoreChecksum?: boolean, ss58Format: Prefix = -1): Uint8Array {
if (isU8a(encoded) || isHex(encoded)) {
return u8aToU8a(encoded);
}
const wrapError = (message: string) => `Decoding ${encoded as string}: ${message}`;
let decoded;
try {
decoded = base58Decode(encoded);
const decoded = base58Decode(encoded);
assert(defaults.allowedEncodedLengths.includes(decoded.length), 'Invalid decoded address length');
const [isValid, endPos, ss58Length, ss58Decoded] = checkAddressChecksum(decoded);
assert(ignoreChecksum || isValid, 'Invalid decoded address checksum');
assert([-1, ss58Decoded].includes(ss58Format), `Expected ss58Format ${ss58Format}, received ${ss58Decoded}`);
return decoded.slice(ss58Length, endPos);
} catch (error) {
throw new Error(wrapError((error as Error).message));
throw new Error(`Decoding ${encoded as string}: ${(error as Error).message}`);
}
// assert(defaults.allowedPrefix.includes(decoded[0] as Prefix), error('Invalid decoded address prefix'));
assert(defaults.allowedEncodedLengths.includes(decoded.length), wrapError('Invalid decoded address length'));
// TODO Unless it is an "use everywhere" prefix, throw an error
// if (ss58Format !== -1 && (decoded[0] !== ss58Format)) {
// console.log(`WARN: Expected ${ss58Format}, found ${decoded[0]}`);
// }
const [isValid, endPos] = checkAddressChecksum(decoded);
assert(ignoreChecksum || isValid, wrapError('Invalid decoded address checksum'));
return decoded.slice(1, endPos);
}
+1 -1
View File
@@ -6,7 +6,7 @@ import { available } from '@polkadot/networks';
export const defaults = {
allowedDecodedLengths: [1, 2, 4, 8, 32, 33],
// publicKey has prefix + 2 checksum bytes, short only prefix + 1 checksum byte
allowedEncodedLengths: [3, 4, 6, 10, 35, 36],
allowedEncodedLengths: [3, 4, 6, 10, 35, 36, 37, 38],
allowedPrefix: available.map(({ prefix }) => prefix),
prefix: 42
};
+76 -10
View File
@@ -7,6 +7,40 @@ import { encodeAddress } from '.';
const keyring = createTestPairs({ type: 'ed25519' }, false);
const SUBKEY = [
{
address: '5DA4D4GL5iakrn22h5uKoevgvo18Pqj5BcdEUv8etEDPdijA',
publicKey: '0x3050f8456519829fe03302da802d22d3233a5f4037b9a3e2bcc403ccfcb2d735',
ss58Format: 42
},
{
// ecdsa
address: '4pbsSkWcBaYoFHrKJZp5fDVUKbqSYD9dhZZGvpp3vQ5ysVs5ybV',
publicKey: '0x035676109c54b9a16d271abeb4954316a40a32bcce023ac14c8e26e958aa68fba9',
ss58Format: 200
},
{
address: 'yGF4JP7q5AK46d1FPCEm9sYQ4KooSjHMpyVAjLnsCSWVafPnf',
publicKey: '0x66cd6cf085627d6c85af1aaf2bd10cf843033e929b4e3b1c2ba8e4aa46fe111b',
ss58Format: 255
},
{
address: 'yGDYxQatQwuxqT39Zs4LtcTnpzE12vXb7ZJ6xpdiHv6gTu1hF',
publicKey: '0x242fd5a078ac6b7c3c2531e9bcf1314343782aeb58e7bc6880794589e701db55',
ss58Format: 255
},
{
address: 'mHm8k9Emsvyfp3piCauSH684iA6NakctF8dySQcX94GDdrJrE',
publicKey: '0x44d5a3ac156335ea99d33a83c57c7146c40c8e2260a8a4adf4e7a86256454651',
ss58Format: 4242
},
{
address: 'r6Gr4gaMP8TsjhFbqvZhv3YvnasugLiRJpzpRHifsqqG18UXa',
publicKey: '0x88f01441682a17b52d6ae12d1a5670cf675fd254897efabaa5069eb3a701ab73',
ss58Format: 14269
}
];
describe('encode', (): void => {
it('encodes an address to a valid value', (): void => {
expect(
@@ -16,8 +50,8 @@ describe('encode', (): void => {
it('can re-encode an address', (): void => {
expect(
encodeAddress('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 68)
).toEqual('7sL6eNJj5ZGV5cn3hhV2deRUsivXfBfMH76wCALCqWj1EKzv');
encodeAddress('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 2)
).toEqual('HNZata7iMYWmk5RvZRTiAsSDhV8366zq2YGb3tLH5Upf74F');
});
it('can re-encode an address to Polkadot live', (): void => {
@@ -45,33 +79,33 @@ describe('encode', (): void => {
it('encodes a 1-byte address (with prefix)', (): void => {
expect(
encodeAddress(
new Uint8Array([1]), 68
new Uint8Array([1]), 2
)
).toEqual('PqtB');
).toEqual('g4b');
});
it('encodes a 2-byte address', (): void => {
expect(
encodeAddress(
new Uint8Array([0, 1]), 68
new Uint8Array([0, 1]), 2
)
).toEqual('2jpAFn');
).toEqual('3xygo');
});
it('encodes a 4-byte address', (): void => {
expect(
encodeAddress(
new Uint8Array([1, 2, 3, 4]), 68
new Uint8Array([1, 2, 3, 4]), 2
)
).toEqual('as7QnGMf');
).toEqual('zswfoZa');
});
it('encodes a 8-byte address', (): void => {
expect(
encodeAddress(
new Uint8Array([42, 44, 10, 0, 0, 0, 0, 0]), 68
new Uint8Array([42, 44, 10, 0, 0, 0, 0, 0]), 2
)
).toEqual('4q7qY5RBG7Z4wv');
).toEqual('848Gh2GcGaZia');
});
it('encodes an 33-byte address', (): void => {
@@ -79,4 +113,36 @@ describe('encode', (): void => {
encodeAddress('0x03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077')
).toEqual('KWCv1L3QX9LDPwY4VzvLmarEmXjVJidUzZcinvVnmxAJJCBou');
});
it('encodes with 2 byte prefix', (): void => {
expect(
encodeAddress(keyring.alice.publicKey, 255)
).toEqual('yGHU8YKprxHbHdEv7oUK4rzMZXtsdhcXVG2CAMyC9WhzhjH2k');
});
SUBKEY.forEach(({ address, publicKey, ss58Format }, index): void => {
it(`encodes with Subkey equality (${index})`, (): void => {
expect(
encodeAddress(publicKey, ss58Format)
).toEqual(address);
});
});
it('does not encode for > 16,383, < 0', (): void => {
expect(
() => encodeAddress(keyring.alice.publicKey, -1)
).toThrow(/range ss58Format specified/);
expect(
() => encodeAddress(keyring.alice.publicKey, 16384)
).toThrow(/range ss58Format specified/);
});
it('does not encode reserved', (): void => {
expect(
() => encodeAddress(keyring.alice.publicKey, 46)
).toThrow(/range ss58Format specified/);
expect(
() => encodeAddress(keyring.alice.publicKey, 47)
).toThrow(/range ss58Format specified/);
});
});
+13 -3
View File
@@ -15,13 +15,23 @@ export function encodeAddress (_key: Uint8Array | string, ss58Format: Prefix = d
// decode it, this means we can re-encode an address
const key = decodeAddress(_key);
assert(ss58Format >= 0 && ss58Format <= 16383 && ![46, 47].includes(ss58Format), 'Out of range ss58Format specified');
assert(defaults.allowedDecodedLengths.includes(key.length), `Expected a valid key to convert, with length ${defaults.allowedDecodedLengths.join(', ')}`);
const isPublicKey = [32, 33].includes(key.length);
const input = u8aConcat(new Uint8Array([ss58Format]), key);
const hash = sshash(input);
const input = u8aConcat(
new Uint8Array(
ss58Format < 64
? [ss58Format]
: [
((ss58Format & 0b0000_0000_1111_1100) >> 2) | 0b0100_0000,
(ss58Format >> 8) | ((ss58Format & 0b0000_0000_0000_0011) << 6)
]
),
key
);
return base58Encode(
u8aConcat(input, hash.subarray(0, isPublicKey ? 2 : 1))
u8aConcat(input, sshash(input).subarray(0, isPublicKey ? 2 : 1))
);
}
+1 -1
View File
@@ -28,7 +28,7 @@ describe('addressEq', (): void => {
expect(
addressEq(
'5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
'7sL6eNJj5ZGV5cn3hhV2deRUsivXfBfMH76wCALCqWj1EKzv'
'15oF4uVJwmo4TdGW7VfQxNLavjCXviqxT9S1MgbjMNHr6Sp5'
)
).toEqual(true);
});
@@ -5,7 +5,7 @@ import { encodeAddress, setSS58Format } from '.';
describe('setSS58Format', (): void => {
beforeEach((): void => {
setSS58Format(68);
setSS58Format(2);
});
it('sets and allows encoding using', (): void => {
@@ -13,6 +13,6 @@ describe('setSS58Format', (): void => {
encodeAddress(
new Uint8Array([1])
)
).toEqual('PqtB');
).toEqual('g4b');
});
});
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
export { hdLedger } from './ledger';
@@ -0,0 +1,29 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { BN_EIGHT, bnToU8a, u8aConcat, u8aToBn } from '@polkadot/util';
import { hmacSha512 } 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);
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 }
).subarray(0, 32),
bnToU8a(
u8aToBn(kr, { isLe: true }).iadd(u8aToBn(z.subarray(32, 64), { isLe: true })),
{ bitLength: 512, isLe: true }
).subarray(0, 32),
hmacSha512(cc, data).subarray(32, 64)
);
}
@@ -0,0 +1,56 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { u8aToHex } from '@polkadot/util';
import { hdLedger } from '..';
const MNE_0 = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about';
const MNE_1 = 'open jelly jeans corn ketchup supreme brief element armed lens vault weather original scissors rug priority vicious lesson raven spot gossip powder person volcano';
const TESTS = {
Kusama: {
slip44: 0x01b2,
tests: [
{
ed25519: '0x98cb4e14e0e08ea876f88d728545ea7572dc07dbbe69f1731c418fb827e69d41',
index: [0, 0],
mnemonic: MNE_0
},
{
ed25519: '0x70e9010e84c81095aaa5f63b1c5a6a66a1dcbec017a23c2f3b7a1b08fe5ea65a',
index: [0, 0],
mnemonic: MNE_1
},
{
ed25519: '0xf06730efb1e6ea59ac752a7c3620fade3909062fb88597856cc3af72045fa65a',
index: [5, 7],
mnemonic: MNE_1
}
]
},
Polkadot: {
slip44: 0x80000162,
tests: [
{
ed25519: '0xe8c68348586d53e4e8d1a864b0e4e17c75e4eb06e0c63c1432bef2ba29e69d41',
index: [0, 0],
mnemonic: MNE_0
}
]
}
};
describe('ledgerDerive', (): void => {
Object.entries(TESTS).forEach(([network, { slip44, tests }]): void => {
tests.forEach(({ ed25519, index: [account, address], mnemonic }, index): void => {
it(`derives a known ed25519 seed for ${network} (${index})`, (): void => {
expect(u8aToHex(
hdLedger(mnemonic, `m/44'/${slip44}'/${account}'/0'/${address}'`)
.secretKey
.slice(0, 32)
)).toEqual(ed25519);
});
});
});
});
@@ -0,0 +1,29 @@
// 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 { mnemonicValidate } from '../../mnemonic';
import { naclKeypairFromSeed } from '../../nacl';
import { ledgerDerivePrivate } from './derivePrivate';
import { ledgerMaster } from './master';
import { ledgerValidatePath } from './validatePath';
const HARDENED = 0x80000000;
export function hdLedger (mnemonic: string, path: string): Keypair {
assert(mnemonicValidate(mnemonic), 'Invalid mnemonic passed to ledger derivation');
assert(ledgerValidatePath(path), 'Invalid derivation path');
return naclKeypairFromSeed(
path
.split('/')
.slice(1)
.map((n) => parseInt(n.replace("'", ''), 10))
.map((n) => (n < HARDENED) ? (n + HARDENED) : n)
.reduce((x, n) => ledgerDerivePrivate(x, n), ledgerMaster(mnemonic))
.slice(0, 32)
);
}
@@ -0,0 +1,17 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { u8aToHex } from '@polkadot/util';
import { ledgerMaster } from './master';
const MNEMONIC = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about';
const XPRV = '0x402b03cd9c8bed9ba9f9bd6cd9c315ce9fcc59c7c25d37c85a36096617e69d418e35cb4a3b737afd007f0688618f21a8831643c0e6c77fc33c06026d2a0fc93832596435e70647d7d98ef102a32ea40319ca8fb6c851d7346d3bd8f9d1492658';
describe('ledgerDerive', (): void => {
it('derives a known master xprv', (): void => {
expect(u8aToHex(
ledgerMaster(MNEMONIC)
)).toEqual(XPRV);
});
});
@@ -0,0 +1,26 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { u8aConcat } from '@polkadot/util';
import { hmacSha256, hmacSha512 } from '../../hmac';
import { mnemonicToSeedSync } from '../../mnemonic/bip39';
const ED25519_CRYPTO = 'ed25519 seed';
// gets an xprv from a mnemonic
export function ledgerMaster (mnemonic: string): Uint8Array {
const seed = mnemonicToSeedSync(mnemonic);
const chainCode = hmacSha256(ED25519_CRYPTO, new Uint8Array([1, ...seed]));
let priv;
while (!priv || (priv[31] & 0b0010_0000)) {
priv = hmacSha512(ED25519_CRYPTO, priv || seed);
}
priv[0] &= 0b1111_1000;
priv[31] &= 0b0111_1111;
priv[31] |= 0b0100_0000;
return u8aConcat(priv, chainCode);
}
@@ -0,0 +1,14 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
export function ledgerValidatePath (path: string): boolean {
if (!path.startsWith('m/')) {
return false;
}
return !path
.split('/')
.slice(1)
.map((n) => parseInt(n.replace("'", ''), 10))
.some((n) => isNaN(n));
}
+5
View File
@@ -0,0 +1,5 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
export { hmacSha256 } from './sha256';
export { hmacSha512 } from './sha512';
+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 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());
}
+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 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());
}
+2
View File
@@ -12,6 +12,8 @@ export * from './base64';
export * from './blake2';
export * from './crypto';
export * from './ethereum';
export * from './hd';
export * from './hmac';
export * from './keccak';
export * from './key';
export * from './mnemonic';
+3 -7
View File
@@ -15,7 +15,7 @@
import hash from 'hash.js';
import { assert, u8aToU8a } from '@polkadot/util';
import { assert, stringToU8a, u8aToU8a } from '@polkadot/util';
import { pbkdf2Encode } from '../pbkdf2';
import { randomAsU8a } from '../random/asU8a';
@@ -45,13 +45,9 @@ function deriveChecksumBits (entropyBuffer: Uint8Array): string {
return bytesToBinary(Array.from(result)).slice(0, CS);
}
function salt (password?: string): string {
return 'mnemonic' + (password || '');
}
export function mnemonicToSeedSync (mnemonic: string, password?: string): Uint8Array {
const mnemonicBuffer = Buffer.from(normalize(mnemonic), 'utf8');
const saltBuffer = Buffer.from(salt(normalize(password)), 'utf8');
const mnemonicBuffer = stringToU8a(normalize(mnemonic));
const saltBuffer = stringToU8a(`mnemonic${normalize(password)}`);
return pbkdf2Encode(mnemonicBuffer, saltBuffer).password;
}
@@ -1,12 +1,12 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { u8aToHex } from '@polkadot/util';
import { u8aEq, u8aToHex } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { mnemonicToLegacySeed } from './';
const MENMONIC = 'seed sock milk update focus rotate barely fade car face mechanic mercy';
const MNEMONIC = 'seed sock milk update focus rotate barely fade car face mechanic mercy';
const SEED = '0x3c121e20de068083b49c2315697fb59a2d9e8643c24e5ea7628132c58969a027';
describe('mnemonicToLegacySeed', (): void => {
@@ -14,11 +14,30 @@ describe('mnemonicToLegacySeed', (): void => {
await waitReady();
});
[undefined, 'foo', 'bar'].forEach((password): void => {
it(`generates Wasm & Js equivalents (password = ${password || 'undefined'})`, (): void => {
expect(
u8aEq(
mnemonicToLegacySeed(MNEMONIC, password, true),
mnemonicToLegacySeed(MNEMONIC, password, false)
)
).toEqual(true);
});
});
[false, true].forEach((onlyJs): void => {
it(`generates a valid seed (onlyJs = ${onlyJs.toString()})`, (): void => {
expect(
u8aToHex(mnemonicToLegacySeed(MENMONIC, undefined, onlyJs))
u8aToHex(mnemonicToLegacySeed(MNEMONIC, undefined, onlyJs))
).toEqual(SEED);
});
});
[false, true].forEach((onlyJs): void => {
it(`fails with non-mnemonics (onlyJs = ${onlyJs.toString()})`, (): void => {
expect(
() => mnemonicToLegacySeed('foo bar baz', undefined, onlyJs)
).toThrow(/mnemonic specified/);
});
});
});
@@ -1,9 +1,11 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { assert } from '@polkadot/util';
import { bip39ToSeed, isReady } from '@polkadot/wasm-crypto';
import { mnemonicToSeedSync } from './bip39';
import { mnemonicValidate } from './validate';
/**
* @name toSeed
@@ -23,6 +25,8 @@ import { mnemonicToSeedSync } from './bip39';
* ```
*/
export function mnemonicToLegacySeed (mnemonic: string, password = '', onlyJs = false): Uint8Array {
assert(mnemonicValidate(mnemonic), 'Invalid bip39 mnemonic specified');
return isReady() && !onlyJs
? bip39ToSeed(mnemonic, password)
: mnemonicToSeedSync(mnemonic, password).subarray(0, 32);
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { u8aToHex } from '@polkadot/util';
import { u8aEq, u8aToHex } from '@polkadot/util';
import tests from '../schnorrkel/keypair/testing';
import { cryptoWaitReady } from '..';
@@ -15,6 +15,17 @@ describe('mnemonicToMiniSecret', (): void => {
await cryptoWaitReady();
});
[undefined, 'foo', 'bar'].forEach((password): void => {
it(`generates Wasm & Js equivalents (password = ${password || 'undefined'})`, (): void => {
expect(
u8aEq(
mnemonicToMiniSecret(MNEMONIC, password, true),
mnemonicToMiniSecret(MNEMONIC, password, false)
)
).toEqual(true);
});
});
[false, true].forEach((onlyJs): void => {
it(`generates a valid seed (onlyJs = ${onlyJs.toString()})`, (): void => {
expect(
@@ -35,4 +46,12 @@ describe('mnemonicToMiniSecret', (): void => {
});
});
});
[false, true].forEach((onlyJs): void => {
it(`fails with non-mnemonics (onlyJs = ${onlyJs.toString()})`, (): void => {
expect(
() => mnemonicToMiniSecret('foo bar baz', undefined, onlyJs)
).toThrow(/mnemonic specified/);
});
});
});
@@ -1,19 +1,22 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { stringToU8a, u8aToBuffer } from '@polkadot/util';
import { assert, stringToU8a } from '@polkadot/util';
import { bip39ToMiniSecret, isReady } from '@polkadot/wasm-crypto';
import { pbkdf2Encode } from '../pbkdf2';
import { mnemonicToEntropy } from './toEntropy';
import { mnemonicValidate } from './validate';
export function mnemonicToMiniSecret (mnemonic: string, password = '', onlyJs = false): Uint8Array {
assert(mnemonicValidate(mnemonic), 'Invalid bip39 mnemonic specified');
if (isReady() && !onlyJs) {
return bip39ToMiniSecret(mnemonic, password);
}
const entropy = u8aToBuffer(mnemonicToEntropy(mnemonic));
const salt = u8aToBuffer(stringToU8a(`mnemonic${password}`));
const entropy = mnemonicToEntropy(mnemonic);
const salt = stringToU8a(`mnemonic${password}`);
// return the first 32 bytes as the seed
return pbkdf2Encode(entropy, salt).password.slice(0, 32);
+10 -8
View File
@@ -15,15 +15,17 @@ describe('pbkdf2Encode', (): void => {
await waitReady();
});
it('has equivalent Wasm & JS results', (): void => {
const salt = randomAsU8a();
[256, 1024, 2048].forEach((rounds): void => {
it(`has equivalent Wasm & JS results (${rounds} rounds)`, (): void => {
const salt = randomAsU8a();
expect(
u8aEq(
pbkdf2Encode(TEST_PASSWORD, salt, 2048, false).password,
pbkdf2Encode(TEST_PASSWORD, salt, 2048, true).password
)
).toBe(true);
expect(
u8aEq(
pbkdf2Encode(TEST_PASSWORD, salt, rounds, false).password,
pbkdf2Encode(TEST_PASSWORD, salt, rounds, true).password
)
).toBe(true);
});
});
[false, true].forEach((onlyJs): void => {
+6 -10
View File
@@ -3,29 +3,25 @@
// Adapted from https://gist.github.com/calvinmetcalf/91e8e84dc63c75f2aa53
import hash from 'hash.js';
import { bnToU8a, u8aConcat } from '@polkadot/util';
import { u8aConcat } from '@polkadot/util';
import { hmacSha512 } from '../hmac';
export function pbkdf2Sync (password: Uint8Array, salt: Uint8Array, rounds: number, len = 64): Uint8Array {
let out = new Uint8Array();
let num = 0;
const block = Buffer.concat([salt, Buffer.from([0, 0, 0, 0])]);
const block = u8aConcat(salt, new Uint8Array(4));
while (out.length < len) {
num++;
block.writeUInt32BE(num, salt.length);
block.set(bnToU8a(num, { bitLength: 32, isLe: false }), salt.length);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
let prev = hash.hmac(hash.sha512, password).update(block).digest();
let prev = hmacSha512(password, block);
const md = prev;
let i = 0;
while (++i < rounds) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
prev = hash.hmac(hash.sha512, password).update(prev).digest();
prev = hmacSha512(password, prev);
let j = -1;
@@ -7,3 +7,5 @@ export { schnorrkelDeriveSoft } from './deriveSoft';
export { schnorrkelKeypairFromSeed } from './keypair/fromSeed';
export { schnorrkelSign } from './sign';
export { schnorrkelVerify } from './verify';
export { schnorrkelVrfSign } from './vrfSign';
export { schnorrkelVrfVerify } from './vrfVerify';
+1 -3
View File
@@ -14,7 +14,5 @@ export function schnorrkelSign (message: Uint8Array | string, { publicKey, secre
assert(publicKey?.length === 32, 'Expected a valid publicKey, 32-bytes');
assert(secretKey?.length === 64, 'Expected a valid secretKey, 64-bytes');
const messageU8a = u8aToU8a(message);
return sr25519Sign(publicKey, secretKey, messageU8a);
return sr25519Sign(publicKey, secretKey, u8aToU8a(message));
}
@@ -9,12 +9,11 @@ import { sr25519Verify } from '@polkadot/wasm-crypto';
* @description Verifies the signature of `message`, using the supplied pair
*/
export function schnorrkelVerify (message: Uint8Array | string, signature: Uint8Array | string, publicKey: Uint8Array | string): boolean {
const messageU8a = u8aToU8a(message);
const publicKeyU8a = u8aToU8a(publicKey);
const signatureU8a = u8aToU8a(signature);
assert(publicKeyU8a.length === 32, `Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
assert(signatureU8a.length === 64, `Invalid signature, received ${signatureU8a.length} bytes, expected 64`);
return sr25519Verify(signatureU8a, messageU8a, publicKeyU8a);
return sr25519Verify(signatureU8a, u8aToU8a(message), publicKeyU8a);
}
@@ -0,0 +1,19 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Keypair } from '../types';
import { assert, u8aToU8a } from '@polkadot/util';
import { vrfSign } from '@polkadot/wasm-crypto';
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 {
assert(secretKey?.length === 64, 'Invalid secretKey, expected 64-bytes');
return vrfSign(secretKey, u8aToU8a(context), u8aToU8a(message), u8aToU8a(extra));
}
@@ -0,0 +1,76 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { stringToU8a, u8aEq } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { randomAsU8a } from '../random/asU8a';
import { schnorrkelKeypairFromSeed } from './keypair/fromSeed';
import { schnorrkelVrfSign } from './vrfSign';
import { schnorrkelVrfVerify } from './vrfVerify';
const MESSAGE = stringToU8a('this is a message');
describe('vrf sign and verify', (): void => {
beforeEach(async (): Promise<void> => {
await waitReady();
});
it('has 96-byte proofs', (): void => {
const pair = schnorrkelKeypairFromSeed(randomAsU8a());
expect(schnorrkelVrfSign(MESSAGE, pair)).toHaveLength(96);
});
it('signing is deterministic', (): void => {
const pair = schnorrkelKeypairFromSeed(randomAsU8a());
const proof1 = schnorrkelVrfSign(MESSAGE, pair);
const proof2 = schnorrkelVrfSign(MESSAGE, pair);
expect(u8aEq(proof1.subarray(0, 32), proof2.subarray(0, 32))).toBe(true);
});
it('can sign and verify a message', (): void => {
const pair = schnorrkelKeypairFromSeed(randomAsU8a());
const proof = schnorrkelVrfSign(MESSAGE, pair);
expect(schnorrkelVrfVerify(MESSAGE, proof, pair.publicKey)).toBe(true);
});
it('can sign and verify a message (with context)', (): void => {
const context = 'my context';
const pair = schnorrkelKeypairFromSeed(randomAsU8a());
const proof = schnorrkelVrfSign(MESSAGE, pair, context);
expect(schnorrkelVrfVerify(MESSAGE, proof, pair.publicKey, context)).toBe(true);
});
it('can sign and verify a message (with context & extra)', (): void => {
const context = 'my context';
const extra = 'some extra transcript data';
const pair = schnorrkelKeypairFromSeed(randomAsU8a());
const proof = schnorrkelVrfSign(MESSAGE, pair, context, extra);
expect(schnorrkelVrfVerify(MESSAGE, proof, pair.publicKey, context, extra)).toBe(true);
});
it('throws error when publicKey lengths do not match', (): void => {
expect(
() => schnorrkelVrfVerify(
new Uint8Array([0x61, 0x62, 0x63, 0x64]),
new Uint8Array(96),
new Uint8Array(31)
)
).toThrow(/Invalid publicKey/);
});
it('throws error when proof lengths do not match', (): void => {
expect(
() => schnorrkelVrfVerify(
new Uint8Array([0x61, 0x62, 0x63, 0x64]),
new Uint8Array(99),
new Uint8Array(32)
)
).toThrow(/Invalid vrfSign/);
});
});
@@ -0,0 +1,21 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { assert, u8aToU8a } from '@polkadot/util';
import { vrfVerify } from '@polkadot/wasm-crypto';
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 {
const publicKeyU8a = u8aToU8a(publicKey);
const proofU8a = u8aToU8a(signOutput);
assert(publicKeyU8a.length === 32, 'Invalid publicKey, expected 32-bytes');
assert(proofU8a.length === 96, 'Invalid vrfSign output, expected 96 bytes');
return vrfVerify(publicKeyU8a, u8aToU8a(context), u8aToU8a(message), u8aToU8a(extra), proofU8a);
}
+5 -6
View File
@@ -1,9 +1,8 @@
{
"name": "@polkadot/util",
"version": "5.3.1",
"version": "5.6.1",
"description": "A collection of useful utilities for @polkadot",
"main": "index.js",
"module": "index.mjs",
"sideEffects": false,
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
@@ -13,12 +12,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.12.5",
"@polkadot/x-textdecoder": "5.3.1",
"@polkadot/x-textencoder": "5.3.1",
"@babel/runtime": "^7.12.13",
"@polkadot/x-textdecoder": "5.6.1",
"@polkadot/x-textencoder": "5.6.1",
"@types/bn.js": "^4.11.6",
"bn.js": "^4.11.9",
"camelcase": "^5.3.1",
"ip-regex": "^4.2.0"
"ip-regex": "^4.3.0"
}
}
+74 -2
View File
@@ -15,6 +15,54 @@ export const BN_ZERO: BN = new BN(0);
*/
export const BN_ONE: BN = new BN(1);
/**
* @name BN_TWO
* @summary BN constant for 2.
*/
export const BN_TWO: BN = new BN(2);
/**
* @name BN_THREE
* @summary BN constant for 3.
*/
export const BN_THREE: BN = new BN(3);
/**
* @name BN_FOUR
* @summary BN constant for 4.
*/
export const BN_FOUR: BN = new BN(4);
/**
* @name BN_FIVE
* @summary BN constant for 5.
*/
export const BN_FIVE: BN = new BN(5);
/**
* @name BN_SIX
* @summary BN constant for 6.
*/
export const BN_SIX: BN = new BN(6);
/**
* @name BN_SEVEN
* @summary BN constant for 7.
*/
export const BN_SEVEN: BN = new BN(7);
/**
* @name BN_EIGHT
* @summary BN constant for 8.
*/
export const BN_EIGHT: BN = new BN(8);
/**
* @name BN_NINE
* @summary BN constant for 9.
*/
export const BN_NINE: BN = new BN(9);
/**
* @name BN_TEN
* @summary BN constant for 10.
@@ -29,6 +77,30 @@ export const BN_HUNDRED: BN = new BN(100);
/**
* @name BN_THOUSAND
* @summary BN constant for 1000.
* @summary BN constant for 1,000.
*/
export const BN_THOUSAND: BN = new BN(1000);
export const BN_THOUSAND: BN = new BN(1_000);
/**
* @name BN_MILLION
* @summary BN constant for 1,000,000.
*/
export const BN_MILLION: BN = new BN(1_000_000);
/**
* @name BN_BILLION
* @summary BN constant for 1,000,000,000.
*/
export const BN_BILLION: BN = new BN(1_000_000_000);
/**
* @name BN_QUINTILL
* @summary BN constant for 1,000,000,000,000,000,000.
*/
export const BN_QUINTILL: BN = BN_BILLION.mul(BN_BILLION);
/**
* @name BN_MAX_INTEGER
* @summary BN constant for MAX_SAFE_INTEGER
*/
export const BN_MAX_INTEGER: BN = new BN(Number.MAX_SAFE_INTEGER);
+27 -16
View File
@@ -5,6 +5,29 @@ import BN from 'bn.js';
import { bnSqrt } from '.';
const TESTS: [string | number | BN | BigInt, string | number][] = [
[0, 0],
[1, 1],
[4, 2],
[256 * 256, 256],
[Number.MAX_SAFE_INTEGER, 94906265],
[new BN(Number.MAX_SAFE_INTEGER).iaddn(256), 94906265],
[12345678n * 12345679n, 12345678],
// test cases below from https://github.com/Aisse-258/bigint-isqrt/blob/f5254b9750841959022461c1353437a07a08f501/test/sqrt-test.js
[
'54866395443885995655625',
'234235768925'
],
[
'82120471531550314555681345949499512621827274120673745141541602816614526075010755373654280259022317599142038423759320355177481886719814621305828811322920076213800348341464996337890625',
'9062034624274524065844376014975805577107171799890766992670739972241112960081909332275390625'
],
[
'2068290204957779940494571454815902632050207752627007664813877111611972735314294907791993008455381265730624848057015476004143868408297250386512042711005577373327434315310235583583151773358353534031397385969275475421659036494173765903706963544628565027679444680637920371210258368358706248446698622704138943704561842220533563976838506992543814273403403362954987589637283890281226038798503294069403370486523697009383229578343444337394508531937972775639593763364402389410142290440075517598007930025487176173228232153685095699851764630884360483051570513804913157899314303269924424908606245851172031453725690942288677622973423417902662711606364188470325930406288190754356367655606430407552275285889968860367977288564364154999338284288438279464648663835830140826171534470717958048887869721791862539529444820484648908879364324577951008050851801647916673254009490596379549192296404841454780884358889449367135382779230574781333008561195244620152128505091883408484094800737142399855337799331037607433934520934135669364954550499058123797911762228642423567268540444910163468496805547450495819213412636594319148417857753712526066272727725420886898680432958409892237191284583904066400736417812258327303739879128916456683685232170600928808798462776174857486589598776587550843543720784829419478239563366491666155716208452087857080883906200829769222868347286071365156305396955420561718593130305703074908891135467193627721682044757187980688062367562451981939375400543212890625',
'45478458691536369397924851088318871329614555665525810477032568598360481742967756704524034986984134271202405190906906195123751965012732122548540879928668891416468847696038707003466943811913626146981446753434347552196868717612248915137033581428310504778371173112125038060138252719589122657221314190626986951627417768579641354255445988772645883238873672997347648890137913979299598785628581961589739331483895853398160785485300758458294999124984266041998145956341386549681176624661615465976970855592467853824812945820721933491609237311130118125761849911376495970746282571994312288380577879004620824004760109618074670810797544446334767103935754106103208789391060008291027361311679876439695844637933763721093782805837690830230712890625'
]
];
describe('bnSqrt', (): void => {
it('fails on < 0 roots', (): void => {
expect(
@@ -12,21 +35,9 @@ describe('bnSqrt', (): void => {
).toThrow(/negative numbers is not supported/);
});
it('finds the sqrt (exact)', (): void => {
expect(
bnSqrt(new BN(256).mul(new BN(256)))
).toEqual(new BN(256));
});
it('finds the sqrt (round)', (): void => {
expect(
bnSqrt(new BN(266))
).toEqual(new BN(16));
});
it('find the sqrt for 1', (): void => {
expect(
bnSqrt(new BN(1))
).toEqual(new BN(1));
TESTS.forEach(([value, expected], index): void => {
it(`calcs for test #${index}`, (): void => {
expect(bnSqrt(value).eq(new BN(expected))).toEqual(true);
});
});
});
+27 -16
View File
@@ -1,20 +1,13 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ToBn } from '../types';
import BN from 'bn.js';
import { assert } from '../assert';
// https://golb.hplar.ch/2018/09/javascript-bigint.html
function newtonIteration (n: BN, x0: BN): BN {
const x1 = n.div(x0).add(x0).shrn(1);
if (x0.eq(x1) || x0.eq(x1.subn(1))) {
return x0;
}
return newtonIteration(n, x1);
}
import { BN_MAX_INTEGER, BN_ONE, BN_ZERO } from '../bn';
import { bnToBn } from './toBn';
/**
* @name bnSqrt
@@ -29,10 +22,28 @@ function newtonIteration (n: BN, x0: BN): BN {
* bnSqrt(new BN(16)).toString(); // => '4'
* ```
*/
export function bnSqrt (value: BN): BN {
assert(value.gten(0), 'square root of negative numbers is not supported');
export function bnSqrt <ExtToBn extends ToBn> (value: ExtToBn | BN | BigInt | string | number | null): BN {
const n = bnToBn(value);
return value.ltn(2)
? value
: newtonIteration(value, new BN(1));
assert(n.gte(BN_ZERO), 'square root of negative numbers is not supported');
// https://stackoverflow.com/questions/53683995/javascript-big-integer-square-root/
// shortcut <= 2^53 - 1 to use the JS utils
if (n.lte(BN_MAX_INTEGER)) {
return new BN(Math.floor(Math.sqrt(n.toNumber())));
}
// Use sqrt(MAX_SAFE_INTEGER) as starting point. since we already know the
// output will be larger than this, we expect this to be a safe start
let x0 = new BN(94906265);
while (true) {
const x1 = n.div(x0).iadd(x0).ishrn(1);
if (x0.eq(x1) || x0.eq(x1.sub(BN_ONE))) {
return x0;
}
x0 = x1;
}
}
+4 -5
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { xglobal } from '@polkadot/x-global';
import { isFunction } from './is/function';
import { isString } from './is/string';
import { assert } from './assert';
@@ -22,8 +24,7 @@ interface PjsChecks extends This {
__polkadotjs: Record<string, VersionPath[]>;
}
type PjsGlobal = NodeJS.Global & PjsChecks;
type PjsWindow = Window & PjsChecks;
type PjsWindow = (Window & This) & PjsChecks;
type FnString = () => string | undefined;
/** @internal */
@@ -33,9 +34,7 @@ function expandPath (path?: string): string {
/** @internal */
function getEntry (name: string): VersionPath[] {
const _global = typeof window !== 'undefined'
? window as PjsWindow
: global as PjsGlobal;
const _global = xglobal as PjsWindow;
if (!_global.__polkadotjs) {
_global.__polkadotjs = {};
@@ -237,4 +237,12 @@ describe('formatBalance', (): void => {
{ power: 24, text: 'Yotta', value: 'Y' }
]);
});
it('can set defaults from array values', (): void => {
formatBalance.setDefaults({ decimals: [12, 24], unit: ['Multi', 'Unit'] });
expect(
formatBalance(TESTVAL)
).toEqual('123.4567 mMulti');
});
});
+17 -4
View File
@@ -15,6 +15,11 @@ interface Defaults {
unit: string;
}
interface SetDefaults {
decimals?: number[] | number;
unit?: string[] | string;
}
interface Options {
decimals?: number;
forceUnit?: string;
@@ -29,7 +34,7 @@ interface BalanceFormatter {
findSi (type: string): SiDef;
getDefaults (): Defaults;
getOptions (decimals?: number): SiDef[];
setDefaults (defaults: Partial<Defaults>): void;
setDefaults (defaults: SetDefaults): void;
}
const DEFAULT_DECIMALS = 0;
@@ -107,9 +112,17 @@ formatBalance.getOptions = (decimals: number = defaultDecimals): SiDef[] => {
// Sets the default decimals to use for formatting (ui-wide)
// eslint-disable-next-line @typescript-eslint/unbound-method
formatBalance.setDefaults = ({ decimals, unit }: Partial<Defaults>): void => {
defaultDecimals = isUndefined(decimals) ? defaultDecimals : decimals;
defaultUnit = isUndefined(unit) ? defaultUnit : unit;
formatBalance.setDefaults = ({ decimals, unit }: SetDefaults): void => {
defaultDecimals = isUndefined(decimals)
? defaultDecimals
: Array.isArray(decimals)
? decimals[0]
: decimals;
defaultUnit = isUndefined(unit)
? defaultUnit
: Array.isArray(unit)
? unit[0]
: unit;
SI[SI_MID].text = defaultUnit;
};
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/x-fetch",
"version": "5.3.1",
"version": "5.6.1",
"description": "A cross-environment fetch replacement",
"browser": "browser.js",
"main": "node.js",
@@ -14,7 +14,8 @@
"bugs": "https://github.com/polkadot-js/common/issues",
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/x-fetch#readme",
"dependencies": {
"@babel/runtime": "^7.12.5",
"@babel/runtime": "^7.12.13",
"@polkadot/x-global": "5.6.1",
"@types/node-fetch": "^2.5.8",
"node-fetch": "^2.6.1"
}
+3 -1
View File
@@ -1,4 +1,6 @@
// Copyright 2017-2021 @polkadot/x-fetch authors & contributors
// SPDX-License-Identifier: Apache-2.0
export const fetch = global.fetch;
import { xglobal } from '@polkadot/x-global';
export const fetch = xglobal.fetch;
+4 -2
View File
@@ -3,6 +3,8 @@
import nodeFetch from 'node-fetch';
export const fetch = typeof global.fetch === 'undefined'
import { xglobal } from '@polkadot/x-global';
export const fetch = typeof xglobal.fetch === 'undefined'
? nodeFetch as unknown as typeof global.fetch
: global.fetch;
: xglobal.fetch;
+11
View File
@@ -0,0 +1,11 @@
# @polkadot/x-global
A cross-environment global object. checks for global > self > window > this.
Install it via `yarn add @polkadot/x-global`
```js
import { xglobal } from '@polkadot/x-global';
console.log(typeof xglobal.TextEncoder);
```
+19
View File
@@ -0,0 +1,19 @@
{
"name": "@polkadot/x-global",
"version": "5.6.1",
"description": "A cross-environment global replacement",
"main": "index.js",
"sideEffects": false,
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
"contributors": [],
"license": "Apache-2.0",
"repository": "github:polkadot-js/common",
"bugs": "https://github.com/polkadot-js/common/issues",
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/x-global#readme",
"dependencies": {
"@babel/runtime": "^7.12.13",
"@types/node-fetch": "^2.5.8",
"node-fetch": "^2.6.1"
}
}
+10
View File
@@ -0,0 +1,10 @@
// Copyright 2017-2021 @polkadot/x-fetch authors & contributors
// SPDX-License-Identifier: Apache-2.0
export const xglobal = typeof global !== 'undefined'
? global
: typeof self !== 'undefined'
? self
: typeof window !== 'undefined'
? window
: this as unknown as (Window & typeof globalThis);
+4 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/x-randomvalues",
"version": "5.3.1",
"version": "5.6.1",
"description": "A cross-environment window.crypto.getRandomValues replacement",
"browser": "browser.js",
"main": "node.js",
@@ -14,9 +14,10 @@
"bugs": "https://github.com/polkadot-js/common/issues",
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/x-randomvalues#readme",
"dependencies": {
"@babel/runtime": "^7.12.5"
"@babel/runtime": "^7.12.13",
"@polkadot/x-global": "5.6.1"
},
"devDependencies": {
"@types/react-native": "^0.63.45"
"@types/react-native": "^0.63.48"
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ let warned = false;
export function insecureRandomValues <T extends Uint8Array> (arr: T): T {
if (!warned) {
console.warn('Using an insecure random number generator, this should only happen when running in a debugger without support for crypto.getRandomValues');
console.warn('Using an insecure random number generator, this should only happen when running in a debugger without support for crypto');
warned = true;
}
+4 -2
View File
@@ -7,6 +7,8 @@
import { NativeModules } from 'react-native';
import { xglobal } from '@polkadot/x-global';
import { insecureRandomValues } from './fallback';
interface RNExt {
@@ -29,9 +31,9 @@ function getRandomValuesGlobal <T extends Uint8Array> (arr: T): T {
return crypto.getRandomValues(arr);
}
export const getRandomValues = typeof global.crypto === 'object' && typeof global.crypto.getRandomValues === 'function'
export const getRandomValues = typeof xglobal.crypto === 'object' && typeof xglobal.crypto.getRandomValues === 'function'
? getRandomValuesGlobal
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-explicit-any
: (typeof (global as any).nativeCallSyncHook === 'undefined' || !NativeModules.ExpoRandom)
: (typeof (xglobal as any).nativeCallSyncHook === 'undefined' || !NativeModules.ExpoRandom)
? insecureRandomValues
: getRandomValuesNative;
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+5
View File
@@ -0,0 +1,5 @@
# @polkadot/x-rxjs
This is a small wrapper around rjx to make it friendly to both Node.js (from .mjs as well as .cjs) as well as bundlers using both esm and cjs modules.
This need wil disappear, once rxjs supports export maps.
+18
View File
@@ -0,0 +1,18 @@
{
"name": "@polkadot/x-rxjs",
"version": "5.6.1",
"description": "A pass-through interface for RxJs (allowing node + mjs usage)",
"main": "index.js",
"sideEffects": false,
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
"contributors": [],
"license": "Apache-2.0",
"repository": "github:polkadot-js/common",
"bugs": "https://github.com/polkadot-js/common/issues",
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/x-rxjs#readme",
"dependencies": {
"@babel/runtime": "^7.12.13",
"rxjs": "^6.6.3"
}
}
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2021 @polkadot/x-rxjs authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from 'rxjs';
+74
View File
@@ -0,0 +1,74 @@
// Copyright 2017-2021 @polkadot/x-rxjs authors & contributors
// SPDX-License-Identifier: Apache-2.0
// This is not great, but while having esm files, rxjs doesn't quite play nicely with
// Node.js mjs files. (Hopefully this improves in 7.0, although no exports map as of yet)
//
// Generated via s/export \{ (.*) \} from .*/exports.$1 = rxjs.$1;/ on rxjs/_esm
// This is or our builder
// @polkadot/dev: exports-node
const rxjs = require('rxjs');
exports.Observable = rxjs.Observable;
exports.ConnectableObservable = rxjs.ConnectableObservable;
exports.GroupedObservable = rxjs.GroupedObservable;
exports.observable = rxjs.observable;
exports.Subject = rxjs.Subject;
exports.BehaviorSubject = rxjs.BehaviorSubject;
exports.ReplaySubject = rxjs.ReplaySubject;
exports.AsyncSubject = rxjs.AsyncSubject;
exports.asap = rxjs.asap;
exports.asapScheduler = rxjs.asapScheduler;
exports.async = rxjs.async;
exports.asyncScheduler = rxjs.asyncScheduler;
exports.queue = rxjs.queue;
exports.queueScheduler = rxjs.queueScheduler;
exports.animationFrame = rxjs.animationFrame;
exports.animationFrameScheduler = rxjs.animationFrameScheduler;
exports.VirtualTimeScheduler = rxjs.VirtualTimeScheduler;
exports.VirtualAction = rxjs.VirtualAction;
exports.Scheduler = rxjs.Scheduler;
exports.Subscription = rxjs.Subscription;
exports.Subscriber = rxjs.Subscriber;
exports.Notification = rxjs.Notification;
exports.NotificationKind = rxjs.NotificationKind;
exports.pipe = rxjs.pipe;
exports.noop = rxjs.noop;
exports.identity = rxjs.identity;
exports.isObservable = rxjs.isObservable;
exports.ArgumentOutOfRangeError = rxjs.ArgumentOutOfRangeError;
exports.EmptyError = rxjs.EmptyError;
exports.ObjectUnsubscribedError = rxjs.ObjectUnsubscribedError;
exports.UnsubscriptionError = rxjs.UnsubscriptionError;
exports.TimeoutError = rxjs.TimeoutError;
exports.bindCallback = rxjs.bindCallback;
exports.bindNodeCallback = rxjs.bindNodeCallback;
exports.combineLatest = rxjs.combineLatest;
exports.concat = rxjs.concat;
exports.defer = rxjs.defer;
exports.empty = rxjs.empty;
exports.forkJoin = rxjs.forkJoin;
exports.from = rxjs.from;
exports.fromEvent = rxjs.fromEvent;
exports.fromEventPattern = rxjs.fromEventPattern;
exports.generate = rxjs.generate;
exports.iif = rxjs.iif;
exports.interval = rxjs.interval;
exports.merge = rxjs.merge;
exports.never = rxjs.never;
exports.of = rxjs.of;
exports.onErrorResumeNext = rxjs.onErrorResumeNext;
exports.pairs = rxjs.pairs;
exports.partition = rxjs.partition;
exports.race = rxjs.race;
exports.range = rxjs.range;
exports.throwError = rxjs.throwError;
exports.timer = rxjs.timer;
exports.using = rxjs.using;
exports.zip = rxjs.zip;
exports.scheduled = rxjs.scheduled;
exports.EMPTY = rxjs.EMPTY;
exports.NEVER = rxjs.NEVER;
exports.config = rxjs.config;
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2021 @polkadot/x-rxjs authors & contributors
// SPDX-License-Identifier: Apache-2.0
export { animationFrame, animationFrameScheduler, ArgumentOutOfRangeError, asap, asapScheduler, async, asyncScheduler, AsyncSubject, BehaviorSubject, bindCallback, bindNodeCallback, combineLatest, concat, config, ConnectableObservable, defer, EMPTY, empty, EmptyError, forkJoin, from, fromEvent, fromEventPattern, generate, GroupedObservable, identity, iif, interval, isObservable, merge, NEVER, never, noop, Notification, NotificationKind, ObjectUnsubscribedError, Observable, observable, of, onErrorResumeNext, pairs, partition, pipe, queue, queueScheduler, race, range, ReplaySubject, scheduled, Scheduler, Subject, Subscriber, Subscription, throwError, TimeoutError, timer, UnsubscriptionError, using, VirtualAction, VirtualTimeScheduler, zip } from 'rxjs/_esm5/index.js';
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2021 @polkadot/x-rxjs authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from 'rxjs/operators';
+117
View File
@@ -0,0 +1,117 @@
// Copyright 2017-2021 @polkadot/x-rxjs authors & contributors
// SPDX-License-Identifier: Apache-2.0
// This is not great, but while having esm files, rxjs doesn't quite play nicely with
// Node.js mjs files. (Hopefully this improves in 7.0, although no exports map as of yet)
//
// Generated via s/export \{ (.*) \} from .*/exports.$1 = rxjs.$1;/ on rxjs/_esm
// This is or our builder, to add the correct exports entry
// @polkadot/dev: exports-node
const operators = require('rxjs/operators');
exports.audit = operators.audit;
exports.auditTime = operators.auditTime;
exports.buffer = operators.buffer;
exports.bufferCount = operators.bufferCount;
exports.bufferTime = operators.bufferTime;
exports.bufferToggle = operators.bufferToggle;
exports.bufferWhen = operators.bufferWhen;
exports.catchError = operators.catchError;
exports.combineAll = operators.combineAll;
exports.combineLatest = operators.combineLatest;
exports.concat = operators.concat;
exports.concatAll = operators.concatAll;
exports.concatMap = operators.concatMap;
exports.concatMapTo = operators.concatMapTo;
exports.count = operators.count;
exports.debounce = operators.debounce;
exports.debounceTime = operators.debounceTime;
exports.defaultIfEmpty = operators.defaultIfEmpty;
exports.delay = operators.delay;
exports.delayWhen = operators.delayWhen;
exports.dematerialize = operators.dematerialize;
exports.distinct = operators.distinct;
exports.distinctUntilChanged = operators.distinctUntilChanged;
exports.distinctUntilKeyChanged = operators.distinctUntilKeyChanged;
exports.elementAt = operators.elementAt;
exports.endWith = operators.endWith;
exports.every = operators.every;
exports.exhaust = operators.exhaust;
exports.exhaustMap = operators.exhaustMap;
exports.expand = operators.expand;
exports.filter = operators.filter;
exports.finalize = operators.finalize;
exports.find = operators.find;
exports.findIndex = operators.findIndex;
exports.first = operators.first;
exports.groupBy = operators.groupBy;
exports.ignoreElements = operators.ignoreElements;
exports.isEmpty = operators.isEmpty;
exports.last = operators.last;
exports.map = operators.map;
exports.mapTo = operators.mapTo;
exports.materialize = operators.materialize;
exports.max = operators.max;
exports.merge = operators.merge;
exports.mergeAll = operators.mergeAll;
exports.mergeMap = operators.mergeMap;
exports.flatMap = operators.flatMap;
exports.mergeMapTo = operators.mergeMapTo;
exports.mergeScan = operators.mergeScan;
exports.min = operators.min;
exports.multicast = operators.multicast;
exports.observeOn = operators.observeOn;
exports.onErrorResumeNext = operators.onErrorResumeNext;
exports.pairwise = operators.pairwise;
exports.partition = operators.partition;
exports.pluck = operators.pluck;
exports.publish = operators.publish;
exports.publishBehavior = operators.publishBehavior;
exports.publishLast = operators.publishLast;
exports.publishReplay = operators.publishReplay;
exports.race = operators.race;
exports.reduce = operators.reduce;
exports.repeat = operators.repeat;
exports.repeatWhen = operators.repeatWhen;
exports.retry = operators.retry;
exports.retryWhen = operators.retryWhen;
exports.refCount = operators.refCount;
exports.sample = operators.sample;
exports.sampleTime = operators.sampleTime;
exports.scan = operators.scan;
exports.sequenceEqual = operators.sequenceEqual;
exports.share = operators.share;
exports.shareReplay = operators.shareReplay;
exports.single = operators.single;
exports.skip = operators.skip;
exports.skipLast = operators.skipLast;
exports.skipUntil = operators.skipUntil;
exports.skipWhile = operators.skipWhile;
exports.startWith = operators.startWith;
exports.subscribeOn = operators.subscribeOn;
exports.switchAll = operators.switchAll;
exports.switchMap = operators.switchMap;
exports.switchMapTo = operators.switchMapTo;
exports.take = operators.take;
exports.takeLast = operators.takeLast;
exports.takeUntil = operators.takeUntil;
exports.takeWhile = operators.takeWhile;
exports.tap = operators.tap;
exports.throttle = operators.throttle;
exports.throttleTime = operators.throttleTime;
exports.throwIfEmpty = operators.throwIfEmpty;
exports.timeInterval = operators.timeInterval;
exports.timeout = operators.timeout;
exports.timeoutWith = operators.timeoutWith;
exports.timestamp = operators.timestamp;
exports.toArray = operators.toArray;
exports.window = operators.window;
exports.windowCount = operators.windowCount;
exports.windowTime = operators.windowTime;
exports.windowToggle = operators.windowToggle;
exports.windowWhen = operators.windowWhen;
exports.withLatestFrom = operators.withLatestFrom;
exports.zip = operators.zip;
exports.zipAll = operators.zipAll;
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2021 @polkadot/x-rxjs authors & contributors
// SPDX-License-Identifier: Apache-2.0
export { audit, auditTime, buffer, bufferCount, bufferTime, bufferToggle, bufferWhen, catchError, combineAll, combineLatest, concat, concatAll, concatMap, concatMapTo, count, debounce, debounceTime, defaultIfEmpty, delay, delayWhen, dematerialize, distinct, distinctUntilChanged, distinctUntilKeyChanged, elementAt, endWith, every, exhaust, exhaustMap, expand, filter, finalize, find, findIndex, first, flatMap, groupBy, ignoreElements, isEmpty, last, map, mapTo, materialize, max, merge, mergeAll, mergeMap, mergeMapTo, mergeScan, min, multicast, observeOn, onErrorResumeNext, pairwise, partition, pluck, publish, publishBehavior, publishLast, publishReplay, race, reduce, refCount, repeat, repeatWhen, retry, retryWhen, sample, sampleTime, scan, sequenceEqual, share, shareReplay, single, skip, skipLast, skipUntil, skipWhile, startWith, subscribeOn, switchAll, switchMap, switchMapTo, take, takeLast, takeUntil, takeWhile, tap, throttle, throttleTime, throwIfEmpty, timeInterval, timeout, timeoutWith, timestamp, toArray, window, windowCount, windowTime, windowToggle, windowWhen, withLatestFrom, zip, zipAll } from 'rxjs/_esm5/operators/index.js';
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/x-textdecoder",
"version": "5.3.1",
"version": "5.6.1",
"description": "A TextDecoder replacement",
"browser": "browser.js",
"main": "node.js",
@@ -14,6 +14,7 @@
"bugs": "https://github.com/polkadot-js/common/issues",
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/x-textdecoder#readme",
"dependencies": {
"@babel/runtime": "^7.12.5"
"@babel/runtime": "^7.12.13",
"@polkadot/x-global": "5.6.1"
}
}
+5 -3
View File
@@ -1,8 +1,10 @@
// Copyright 2017-2021 @polkadot/x-textencoder authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { xglobal } from '@polkadot/x-global';
import { TextDecoder as Fallback } from './fallback';
export const TextDecoder = typeof global.TextDecoder === 'undefined'
? Fallback as unknown as typeof global.TextDecoder
: global.TextDecoder;
export const TextDecoder = typeof xglobal.TextDecoder === 'undefined'
? Fallback as unknown as typeof xglobal.TextDecoder
: xglobal.TextDecoder;
+5 -3
View File
@@ -3,6 +3,8 @@
import util from 'util';
export const TextDecoder = typeof global.TextDecoder === 'undefined'
? util.TextDecoder as unknown as typeof global.TextDecoder
: global.TextDecoder;
import { xglobal } from '@polkadot/x-global';
export const TextDecoder = typeof xglobal.TextDecoder === 'undefined'
? util.TextDecoder as unknown as typeof xglobal.TextDecoder
: xglobal.TextDecoder;
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/x-textencoder",
"version": "5.3.1",
"version": "5.6.1",
"description": "A TextDecoder replacement",
"browser": "browser.js",
"main": "node.js",
@@ -14,6 +14,7 @@
"bugs": "https://github.com/polkadot-js/common/issues",
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/x-textencoder#readme",
"dependencies": {
"@babel/runtime": "^7.12.5"
"@babel/runtime": "^7.12.13",
"@polkadot/x-global": "5.6.1"
}
}
+5 -3
View File
@@ -1,8 +1,10 @@
// Copyright 2017-2021 @polkadot/x-textencoder authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { xglobal } from '@polkadot/x-global';
import { TextEncoder as Fallback } from './fallback';
export const TextEncoder = typeof global.TextEncoder === 'undefined'
? Fallback as unknown as typeof global.TextEncoder
: global.TextEncoder;
export const TextEncoder = typeof xglobal.TextEncoder === 'undefined'
? Fallback as unknown as typeof xglobal.TextEncoder
: xglobal.TextEncoder;
+5 -3
View File
@@ -3,6 +3,8 @@
import util from 'util';
import { xglobal } from '@polkadot/x-global';
class NodeFallback {
#encoder: util.TextEncoder;
@@ -18,6 +20,6 @@ class NodeFallback {
}
}
export const TextEncoder = typeof global.TextEncoder === 'undefined'
? NodeFallback as unknown as typeof global.TextEncoder
: global.TextEncoder;
export const TextEncoder = typeof xglobal.TextEncoder === 'undefined'
? NodeFallback as unknown as typeof xglobal.TextEncoder
: xglobal.TextEncoder;
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/x-ws",
"version": "5.3.1",
"version": "5.6.1",
"description": "A cross-environment WebSocket replacement",
"browser": "browser.js",
"main": "node.js",
@@ -14,7 +14,8 @@
"bugs": "https://github.com/polkadot-js/common/issues",
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/x-ws#readme",
"dependencies": {
"@babel/runtime": "^7.12.5",
"@babel/runtime": "^7.12.13",
"@polkadot/x-global": "5.6.1",
"@types/websocket": "^1.0.1",
"websocket": "^1.0.33"
}
+3 -1
View File
@@ -1,4 +1,6 @@
// Copyright 2017-2021 @polkadot/x-ws authors & contributors
// SPDX-License-Identifier: Apache-2.0
export const WebSocket = global.WebSocket;
import { xglobal } from '@polkadot/x-global';
export const WebSocket = xglobal.WebSocket;
+5 -3
View File
@@ -3,6 +3,8 @@
import ws from 'websocket';
export const WebSocket = typeof global.WebSocket === 'undefined'
? ws.w3cwebsocket as unknown as typeof global.WebSocket
: global.WebSocket;
import { xglobal } from '@polkadot/x-global';
export const WebSocket = typeof xglobal.WebSocket === 'undefined'
? ws.w3cwebsocket as unknown as typeof xglobal.WebSocket
: xglobal.WebSocket;
+8 -1
View File
@@ -19,7 +19,14 @@
"@polkadot/util-crypto/*": [ "packages/util-crypto/src/*" ],
"@polkadot/util": [ "packages/util/src" ],
"@polkadot/util/*": [ "packages/util/src/*" ],
"@polkadot/x-*": [ "packages/x-*/src/browser" ]
"@polkadot/x-fetch": [ "packages/x-fetch/src/browser" ],
"@polkadot/x-global": [ "packages/x-global/src" ],
"@polkadot/x-randomvalues": [ "packages/x-randomvalues/src/browser" ],
"@polkadot/x-rxjs": ["packages/x-rxjs/src"],
"@polkadot/x-rxjs/*": ["packages/x-rxjs/src/*"],
"@polkadot/x-textdecoder": [ "packages/x-textdecoder/src/browser" ],
"@polkadot/x-textencoder": [ "packages/x-textencoder/src/browser" ],
"@polkadot/x-ws": [ "packages/x-ws/src/browser" ]
},
"skipLibCheck": true,
"typeRoots": [
+1033 -887
View File
File diff suppressed because it is too large Load Diff