Compare commits

...
25 Commits
Author SHA1 Message Date
Github Actions 1d8b8b3204 [CI Skip] release/stable 2.16.1
skip-checks: true
2020-06-29 05:19:13 +00:00
Jaco Greeff 4a2e090ef8 2.16 (#623) 2020-06-29 07:15:21 +02:00
Github Actions 8cf8d5b7e8 [CI Skip] release/beta 2.16.0-beta.0
skip-checks: true
2020-06-26 12:49:47 +00:00
Jaco Greeff 8d355ff6fc Local base58 alphabet check for better errors (#622)
* Local base58 alphabet check for better errors

* Rewrite yarn.lock

* Align error return values

* Split base58{Encode, Decode}

* base58Encode input types

* Function names, some docs
2020-06-26 14:46:19 +02:00
Github Actions 72456bb2bd [CI Skip] release/stable 2.15.1
skip-checks: true
2020-06-22 09:33:14 +00:00
Jaco Greeff 87f3fd2827 2.15 (#621) 2020-06-22 11:29:33 +02:00
Github Actions 7254aab68d [CI Skip] release/beta 2.15.0-beta.0
skip-checks: true
2020-06-19 15:39:36 +00:00
Jaco Greeff 95d7160ad0 Test for 0 prefix (#620)
* Test for 0 prefix

* Add test for keyring encodeAddress (& fix)

* Test other branch of ?: check
2020-06-19 17:35:48 +02:00
Github Actions 611b1be481 [CI Skip] release/stable 2.14.1
skip-checks: true
2020-06-16 06:02:06 +00:00
Jaco Greeff 73b35fc188 2.14 (#618) 2020-06-16 07:58:33 +02:00
Github Actions 6c30d5b9fd [CI Skip] release/beta 2.14.0-beta.0
skip-checks: true
2020-06-08 15:58:49 +00:00
Keith Ingram 56d151fe66 Add BN consts and timeToString (#610)
* Add BN consts and timeToString

* docs

* lint

* fixes

* lint

* lint

* add tests, ms

* fix

* test
2020-06-09 03:55:21 +12:00
Github Actions cd20fe6c8b [CI Skip] release/stable 2.13.1
skip-checks: true
2020-06-08 14:03:31 +00:00
Jaco Greeff 28f8ca73aa 2.13 (#616) 2020-06-08 15:59:47 +02:00
Github Actions f4a8bfc0c0 [CI Skip] release/beta 2.13.0-beta.5
skip-checks: true
2020-06-08 12:33:10 +00:00
Jaco Greeff 94b058d6a3 Align bnToHex signature with bnToU8a (#615) 2020-06-08 14:29:40 +02:00
Github Actions 3d7ddb85a2 [CI Skip] release/beta 2.13.0-beta.4
skip-checks: true
2020-06-08 11:35:08 +00:00
Jaco Greeff f7a2bb895f Fix blake2 U8a JS with hex inputs (#614)
* Fix blake2 U8a JS with hex inputs

* Apply suggestions from code review
2020-06-08 13:31:10 +02:00
Github Actions c1bfcc00b6 [CI Skip] release/beta 2.13.0-beta.3
skip-checks: true
2020-06-06 08:08:42 +00:00
Jaco Greeff b16d8e7c26 Bump deps (#612) 2020-06-06 10:05:02 +02:00
Github Actions 2a4b363fcd [CI Skip] release/beta 2.13.0-beta.2
skip-checks: true
2020-06-05 20:17:13 +00:00
Jaco Greeff de689b8e6f Bump deps (#611) 2020-06-05 22:13:55 +02:00
Github Actions 2e72ab920b [CI Skip] release/beta 2.13.0-beta.1
skip-checks: true
2020-06-02 09:44:29 +00:00
Jaco Greeff 565e6baecd Linting 2020-06-02 11:40:25 +02:00
Jaco Greeff 1e15203b6c Reset to beta 2020-06-02 11:24:23 +02:00
36 changed files with 1623 additions and 1323 deletions
+19
View File
@@ -1,5 +1,24 @@
# CHANGELOG
## 2.16.1 Jun 29, 2020
- Adjust `addressCheck` and `encodeAddress` function to check for valid base58 alphabets (better error reporting)
- Rename `createKeySub` to `createKeyDerived` based on changed in Substrate (sub keys now named derived)
## 2.15.1 Jun 22, 2020
- Adjust keyring to no override 0-prefix (Polkadot live) settings with keychain default
## 2.14.1 Jun 16, 2020
- Add `extractTime` utility conversion (Thanks to https://github.com/kwingram25)
## 2.13.1 Jun 8, 2020
- Fix JS blake2 fallback (non-wasm) to correctly deal with hex inputs
- Align `bnToHex` signature with `bnToU8a` (with old/new style)
- Allow `bnTo{Hex,U8a}` to take any value with `.toBn()` signatures
## 2.12.2 Jun 1, 2020
- Fix `isFunction` signature to assert `Function`
+1 -1
View File
@@ -9,5 +9,5 @@
"packages": [
"packages/*"
],
"version": "2.12.2"
"version": "2.16.1"
}
+5 -5
View File
@@ -21,10 +21,10 @@
"test:one": "polkadot-dev-run-test"
},
"devDependencies": {
"@babel/core": "^7.9.6",
"@polkadot/dev": "^0.55.6",
"@polkadot/ts": "^0.3.25",
"@types/jest": "^25.2.3"
"@babel/core": "^7.10.3",
"@polkadot/dev": "^0.55.13",
"@polkadot/ts": "^0.3.26",
"@types/jest": "^26.0.3"
},
"version": "2.12.2"
"version": "2.16.1"
}
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/keyring",
"version": "2.12.2",
"version": "2.16.1",
"description": "Keyring management",
"main": "index.js",
"publishConfig": {
@@ -27,8 +27,8 @@
},
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/keyring#readme",
"dependencies": {
"@babel/runtime": "^7.9.6",
"@polkadot/util": "2.12.2",
"@polkadot/util-crypto": "2.12.2"
"@babel/runtime": "^7.10.3",
"@polkadot/util": "2.16.1",
"@polkadot/util-crypto": "2.16.1"
}
}
+20
View File
@@ -212,4 +212,24 @@ describe('keypair', (): void => {
expect(pair.verify(MESSAGE, signature)).toBe(true);
});
});
describe('util', (): void => {
let keyring: Keyring;
beforeEach((): void => {
keyring = new Keyring({ ss58Format: 42 });
});
it('can re-encode an address to Polkadot live', (): void => {
expect(
keyring.encodeAddress('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 0)
).toEqual('15oF4uVJwmo4TdGW7VfQxNLavjCXviqxT9S1MgbjMNHr6Sp5');
});
it('can re-encode an address to keyring default', (): void => {
expect(
keyring.encodeAddress('15oF4uVJwmo4TdGW7VfQxNLavjCXviqxT9S1MgbjMNHr6Sp5')
).toEqual('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY');
});
});
});
+2 -2
View File
@@ -5,7 +5,7 @@
import { KeypairType, Keypair } from '@polkadot/util-crypto/types';
import { KeyringInstance, KeyringPair, KeyringPair$Json, KeyringPair$Meta, KeyringOptions } from './types';
import { assert, hexToU8a, isHex, stringToU8a } from '@polkadot/util';
import { assert, hexToU8a, isHex, isUndefined, stringToU8a } from '@polkadot/util';
import { decodeAddress, encodeAddress, keyExtractSuri, keyFromPath, naclKeypairFromSeed as naclFromSeed, schnorrkelKeypairFromSeed as schnorrkelFromSeed, secp256k1KeypairFromSeed as secp256k1FromSeed, mnemonicToMiniSecret } from '@polkadot/util-crypto';
import { DEV_PHRASE } from './defaults';
@@ -192,7 +192,7 @@ export default class Keyring implements KeyringInstance {
* @description Encodes the input into an ss58 representation
*/
public encodeAddress = (address: Uint8Array | string, ss58Format?: number): string => {
return encodeAddress(address, ss58Format || this.#ss58);
return encodeAddress(address, isUndefined(ss58Format) ? this.#ss58 : ss58Format);
}
/**
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/util-crypto",
"version": "2.12.2",
"version": "2.16.1",
"description": "A collection of useful crypto utilities for @polkadot",
"main": "index.js",
"keywords": [
@@ -25,17 +25,17 @@
},
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util-crypto#readme",
"dependencies": {
"@babel/runtime": "^7.9.6",
"@polkadot/util": "2.12.2",
"@babel/runtime": "^7.10.3",
"@polkadot/util": "2.16.1",
"@polkadot/wasm-crypto": "^1.2.1",
"base-x": "^3.0.8",
"bip39": "^3.0.2",
"blakejs": "^1.1.0",
"bn.js": "^5.1.2",
"bs58": "^4.0.1",
"elliptic": "^6.5.2",
"elliptic": "^6.5.3",
"js-sha3": "^0.8.0",
"pbkdf2": "^3.0.17",
"pbkdf2": "^3.1.1",
"tweetnacl": "^1.0.3",
"xxhashjs": "^0.2.2"
},
@@ -17,6 +17,12 @@ describe('checkAddress', (): void => {
).toEqual([true, null]);
});
it('fails when an invalid base58 character is supplied', (): void => {
expect(
checkAddress('5EnxIUmEbw8DkENKiYuZ1DwQuMoB2UWEQJZZXrTsxoz7SpgG', 2)
).toEqual([false, 'Invalid base58 character "I" (0x49) at index 4']);
});
it('fails with invalid prefix when checking Substrate against Kusama prefix', (): void => {
expect(
checkAddress('5EnxxUmEbw8DkENKiYuZ1DwQuMoB2UWEQJZZXrTsxoz7SpgG', 2)
+14 -3
View File
@@ -4,13 +4,24 @@
import { Prefix } from './types';
import bs58 from 'bs58';
import base58Decode from '../base58/decode';
import checkChecksum from './checkChecksum';
import defaults from './defaults';
/**
* @name checkAddress
* @summary Validates an ss58 address.
* @description
* From the provided input, validate that the address is a valid input.
*/
export default function check (address: string, prefix: Prefix): [boolean, string | null] {
const decoded = bs58.decode(address);
let decoded;
try {
decoded = base58Decode(address);
} catch (error) {
return [false, (error as Error).message];
}
if (decoded[0] !== prefix) {
return [false, `Prefix mismatch, expected ${prefix}, found ${decoded[0]}`];
@@ -94,4 +94,10 @@ describe('decode', (): void => {
(): Uint8Array => decode('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDwU')
).toThrow(/address checksum/);
});
it('fails when invalid base58 encoded address is found', (): void => {
expect(
() => u8aToHex(decode('F3opIRbN5ZbjJNU511Kj2TLuzFcDq9BGduA9TgiECafpg29'))
).toThrow(/Decoding F3opIRbN5ZbjJNU511Kj2TLuzFcDq9BGduA9TgiECafpg29: Invalid base58 character "I" \(0x49\) at index 4/);
});
});
+12 -6
View File
@@ -6,9 +6,9 @@ import { Prefix } from './types';
// Original implementation: https://github.com/paritytech/polka-ui/blob/4858c094684769080f5811f32b081dd7780b0880/src/polkadot.js#L6
import bs58 from 'bs58';
import { assert, bufferToU8a, isHex, isU8a, u8aToU8a } from '@polkadot/util';
import { assert, isHex, isU8a, u8aToU8a } from '@polkadot/util';
import base58Decode from '../base58/decode';
import checkChecksum from './checkChecksum';
import defaults from './defaults';
@@ -18,11 +18,17 @@ export default function decode (encoded: string | Uint8Array, ignoreChecksum?: b
return u8aToU8a(encoded);
}
const decoded = bufferToU8a(bs58.decode(encoded));
const error = (message: string) => `Decoding ${encoded as string}: ${message}`;
const wrapError = (message: string) => `Decoding ${encoded as string}: ${message}`;
let decoded;
try {
decoded = base58Decode(encoded);
} catch (error) {
throw new Error(wrapError((error as Error).message));
}
// assert(defaults.allowedPrefix.includes(decoded[0] as Prefix), error('Invalid decoded address prefix'));
assert(defaults.allowedEncodedLengths.includes(decoded.length), error('Invalid decoded address length'));
assert(defaults.allowedEncodedLengths.includes(decoded.length), wrapError('Invalid decoded address length'));
// TODO Unless it is an "use everywhere" prefix, throw an error
// if (decoded[0] !== prefix) {
@@ -31,7 +37,7 @@ export default function decode (encoded: string | Uint8Array, ignoreChecksum?: b
const [isValid, endPos] = checkChecksum(decoded);
assert(ignoreChecksum || isValid, error('Invalid decoded address checksum'));
assert(ignoreChecksum || isValid, wrapError('Invalid decoded address checksum'));
return decoded.slice(1, endPos);
}
@@ -21,6 +21,12 @@ describe('encode', (): void => {
).toEqual('7sL6eNJj5ZGV5cn3hhV2deRUsivXfBfMH76wCALCqWj1EKzv');
});
it('can re-encode an address to Polkadot live', (): void => {
expect(
encode('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 0)
).toEqual('15oF4uVJwmo4TdGW7VfQxNLavjCXviqxT9S1MgbjMNHr6Sp5');
});
it('fails when non-valid publicKey provided', (): void => {
expect(
(): string => encode(
+4 -6
View File
@@ -6,9 +6,9 @@ import { Prefix } from './types';
// Original implementation: https://github.com/paritytech/polka-ui/blob/4858c094684769080f5811f32b081dd7780b0880/src/polkadot.js#L34
import bs58 from 'bs58';
import { assert, u8aConcat, u8aToBuffer } from '@polkadot/util';
import { assert, u8aConcat } from '@polkadot/util';
import base58Encode from '../base58/encode';
import decode from './decode';
import defaults from './defaults';
import sshash from './sshash';
@@ -23,9 +23,7 @@ export default function encode (_key: Uint8Array | string, ss58Format: Prefix =
const input = u8aConcat(new Uint8Array([ss58Format]), key);
const hash = sshash(input);
return bs58.encode(
u8aToBuffer(
u8aConcat(input, hash.subarray(0, isPublicKey ? 2 : 1))
)
return base58Encode(
u8aConcat(input, hash.subarray(0, isPublicKey ? 2 : 1))
);
}
+2 -2
View File
@@ -5,7 +5,7 @@
import checkAddress from './check';
import checkAddressChecksum from './checkChecksum';
import createKeyMulti from './keyMulti';
import createKeySub from './keySub';
import createKeyDerived from './keyDerived';
import decodeAddress from './decode';
import encodeAddress from './encode';
import addressEq from './eq';
@@ -16,8 +16,8 @@ export {
addressEq,
checkAddress,
checkAddressChecksum,
createKeyDerived,
createKeyMulti,
createKeySub,
decodeAddress,
encodeAddress,
setSS58Format,
@@ -2,12 +2,12 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import createKeySub from './keySub';
import createKeyDerived from './keyDerived';
describe('createKeySub', (): void => {
it('matches sub accounts with Rust', (): void => {
expect(
createKeySub(new Uint8Array([1, 0, 0, 0, 0, 0, 0, 0]), 0)
createKeyDerived(new Uint8Array([1, 0, 0, 0, 0, 0, 0, 0]), 0)
).toEqual(
new Uint8Array([234, 236, 28, 96, 177, 168, 152, 193, 71, 179, 226, 102, 179, 155, 188, 240, 90, 182, 21, 175, 47, 47, 250, 179, 178, 0, 81, 222, 70, 56, 52, 234])
);
@@ -15,7 +15,7 @@ describe('createKeySub', (): void => {
it('creates a valid subkey', (): void => {
expect(
createKeySub('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1)
createKeyDerived('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1)
).toEqual(
new Uint8Array([248, 19, 86, 209, 254, 89, 84, 48, 54, 128, 166, 239, 153, 212, 143, 34, 191, 60, 210, 50, 39, 77, 122, 71, 29, 60, 247, 198, 95, 101, 246, 83])
);
@@ -10,7 +10,7 @@ import decodeAddress from './decode';
const PREFIX = stringToU8a('modlpy/utilisuba');
export default function createKeySub (who: Uint8Array | string, index: BigInt | BN | number): Uint8Array {
export default function createKeyDerived (who: Uint8Array | string, index: BigInt | BN | number): Uint8Array {
return blake2AsU8a(
u8aConcat(
PREFIX,
+25
View File
@@ -0,0 +1,25 @@
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import bs58 from 'bs58';
import { bufferToU8a } from '@polkadot/util';
// copied from bs58
const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
/**
* @name base58Decode
* @summary Decodes a base58 value.
* @description
* From the provided input, decode the base58 and return the result as an `Uint8Array`.
*/
export default function base58Decode (value: string): Uint8Array {
for (let i = 0; i < value.length; i++) {
if (!BASE58_ALPHABET.includes(value[i])) {
throw new Error(`Invalid base58 character "${value[i]}" (0x${value.charCodeAt(i).toString(16)}) at index ${i}`);
}
}
return bufferToU8a(bs58.decode(value));
}
+18
View File
@@ -0,0 +1,18 @@
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import bs58 from 'bs58';
import { u8aToBuffer, u8aToU8a } from '@polkadot/util';
/**
* @name base58Encode
* @summary Creates a base58 value.
* @description
* From the provided input, create the base58 and return the result as a string.
*/
export default function base58Encode (value: Uint8Array | string | Buffer | number[]): string {
return bs58.encode(
u8aToBuffer(u8aToU8a(value))
);
}
+10
View File
@@ -0,0 +1,10 @@
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
/**
* @summary Encode and decode base58 values
*/
export { default as base58Decode } from './decode';
export { default as base58Encode } from './encode';
@@ -43,4 +43,18 @@ describe('blake2AsU8a', (): void => {
hexToU8a('0xba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923')
);
});
it('has equivalent Wasm/Js outputs on hex inputs', (): void => {
const a = blake2AsU8a('0x123456', 256, null, false);
const b = blake2AsU8a('0x123456', 256, null, true);
expect(a).toEqual(b);
});
it('has equivalent Wasm/Js outputs with key inputs', (): void => {
const a = blake2AsU8a('0x123456', 256, new Uint8Array([1, 2]), false);
const b = blake2AsU8a('0x123456', 256, new Uint8Array([1, 2]), true);
expect(a).toEqual(b);
});
});
+3 -3
View File
@@ -20,10 +20,10 @@ import { blake2b, isReady } from '@polkadot/wasm-crypto';
* blake2AsU8a('abc'); // => [0xba, 0x80, 0xa53, 0xf98, 0x1c, 0x4d, 0x0d]
* ```
*/
export default function blake2AsU8a (data: Uint8Array | string, bitLength = 256, key: Uint8Array | null = null): Uint8Array {
export default function blake2AsU8a (data: Uint8Array | string, bitLength = 256, key: Uint8Array | null = null, onlyJs = false): Uint8Array {
const byteLength = Math.ceil(bitLength / 8);
return isReady()
return isReady() && !onlyJs
? blake2b(u8aToU8a(data), u8aToU8a(key), byteLength)
: blakejs.blake2b(data, key, byteLength);
: blakejs.blake2b(u8aToU8a(data), key, byteLength);
}
+1
View File
@@ -10,6 +10,7 @@ export * from './init';
// all internal exports
export * from './address';
export * from './base58';
export * from './blake2';
export * from './keccak';
export * from './key';
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/util",
"version": "2.12.2",
"version": "2.16.1",
"description": "A collection of useful utilities for @polkadot",
"main": "index.js",
"keywords": [
@@ -25,11 +25,11 @@
},
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util#readme",
"dependencies": {
"@babel/runtime": "^7.9.6",
"@babel/runtime": "^7.10.3",
"@types/bn.js": "^4.11.6",
"bn.js": "^5.1.2",
"camelcase": "^5.3.1",
"chalk": "^4.0.0",
"chalk": "^4.1.0",
"ip-regex": "^4.1.0"
}
}
+38
View File
@@ -0,0 +1,38 @@
// Copyright 2017-2020 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { BN_ZERO, BN_ONE, BN_TEN, BN_HUNDRED, BN_THOUSAND } from '.';
import BN from 'bn.js';
describe('consts', (): void => {
it('BN_ZERO equals 0', (): void => {
expect(
BN_ZERO
).toEqual(new BN(0));
});
it('BN_ONE equals 1', (): void => {
expect(
BN_ONE
).toEqual(new BN(1));
});
it('BN_TEN equals 10', (): void => {
expect(
BN_TEN
).toEqual(new BN(10));
});
it('BN_HUNDRED equals 100', (): void => {
expect(
BN_HUNDRED
).toEqual(new BN(100));
});
it('BN_THOUSAND equals 1000', (): void => {
expect(
BN_THOUSAND
).toEqual(new BN(1000));
});
});
+43
View File
@@ -0,0 +1,43 @@
// Copyright 2017-2020 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import BN from 'bn.js';
/**
* @name BN_ZERO
* @summary BN constant for 0.
*/
const BN_ZERO: BN = new BN(0);
/**
* @name BN_ONE
* @summary BN constant for 1.
*/
const BN_ONE: BN = new BN(1);
/**
* @name BN_TEN
* @summary BN constant for 10.
*/
const BN_TEN: BN = new BN(10);
/**
* @name BN_HUNDRED
* @summary BN constant for 100.
*/
const BN_HUNDRED: BN = new BN(100);
/**
* @name BN_THOUSAND
* @summary BN constant for 1000.
*/
const BN_THOUSAND: BN = new BN(1000);
export {
BN_ZERO,
BN_ONE,
BN_TEN,
BN_HUNDRED,
BN_THOUSAND
};
+1
View File
@@ -6,6 +6,7 @@
* @summary Utility methods to convert to and from `BN` objects
*/
export * from './consts';
export { default as bnFromHex } from './fromHex';
export { default as bnMax } from './max';
export { default as bnMin } from './min';
+6
View File
@@ -25,6 +25,12 @@ describe('bnToHex', (): void => {
).toBe('0x0080');
});
it('converts BN values to a prefixed hex representation (bitLength + le)', (): void => {
expect(
bnToHex(new BN(128), 16, true)
).toBe('0x8000');
});
it('converts BN values to a prefixed hex representation (LE)', (): void => {
expect(
bnToHex(new BN(128), { bitLength: 16, isLe: true })
+8 -3
View File
@@ -2,11 +2,12 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ToBn, ToBnOptions } from '../types';
import BN from 'bn.js';
import isNumber from '../is/number';
import bnToU8a from './toU8a';
import { ToBnOptions } from '../types';
import { u8aToHex } from '../u8a';
const ZERO_STR = '0x00';
@@ -30,7 +31,9 @@ interface Options extends ToBnOptions {
* bnToHex(new BN(0x123456)); // => '0x123456'
* ```
*/
export default function bnToHex (value?: BN | BigInt | number | null, options: number | Options = { bitLength: -1, isLe: false, isNegative: false }): string {
function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null, options?: Options): string;
function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null, bitLength?: number, isLe?: boolean): string;
function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null, arg1: number | Options = { bitLength: -1, isLe: false, isNegative: false }, arg2?: boolean): string {
if (!value) {
return ZERO_STR;
}
@@ -39,8 +42,10 @@ export default function bnToHex (value?: BN | BigInt | number | null, options: n
isLe: false,
isNegative: false,
// Backwards-compatibility
...(isNumber(options) ? { bitLength: options } : options)
...(isNumber(arg1) ? { bitLength: arg1, isLe: arg2 } : arg1)
};
return u8aToHex(bnToU8a(value, _options));
}
export default bnToHex;
+5 -4
View File
@@ -2,11 +2,12 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ToBn, ToBnOptions } from '../types';
import BN from 'bn.js';
import isNumber from '../is/number';
import bnToBn from './toBn';
import { ToBnOptions } from '../types';
interface Options extends ToBnOptions {
bitLength?: number;
@@ -26,9 +27,9 @@ interface Options extends ToBnOptions {
* bnToU8a(new BN(0x1234)); // => [0x12, 0x34]
* ```
*/
function bnToU8a (value: BN | BigInt | number | null, options?: Options): Uint8Array;
function bnToU8a (value: BN | BigInt | number | null, bitLength?: number, isLe?: boolean): Uint8Array;
function bnToU8a (value: BN | BigInt | number | null, arg1: number | Options = { bitLength: -1, isLe: true, isNegative: false }, arg2?: boolean): Uint8Array {
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null, options?: Options): Uint8Array;
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null, bitLength?: number, isLe?: boolean): Uint8Array;
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null, arg1: number | Options = { bitLength: -1, isLe: true, isNegative: false }, arg2?: boolean): Uint8Array {
const _options: Options = {
bitLength: -1,
isLe: true,
+20
View File
@@ -0,0 +1,20 @@
// Copyright 2017-2020 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { extractTime } from '.';
describe('extractTime', (): void => {
const milliseconds = 1e9 + 123;
it('extracts time components correctly', (): void => {
expect(extractTime(milliseconds))
.toEqual({
days: 11,
hours: 13,
milliseconds: 123,
minutes: 46,
seconds: 40
});
});
});
+73
View File
@@ -0,0 +1,73 @@
// Copyright 2017-2020 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Time } from './types';
const HRS = 60 * 60;
const DAY = HRS * 24;
/**
* @name addTime
* @summary Add together two Time arrays
*/
function addTime (a: Time, b: Time): Time {
return {
days: a.days + b.days,
hours: a.hours + b.hours,
milliseconds: a.milliseconds + b.milliseconds,
minutes: a.minutes + b.minutes,
seconds: a.seconds + b.seconds
};
}
const ZERO = { days: 0, hours: 0, milliseconds: 0, minutes: 0, seconds: 0 };
/**
* @name extractTime
* @summary Convert a quantity of seconds to Time array representing accumulated {days, minutes, hours, seconds, milliseconds}
* @example
* <BR>
*
* ```javascript
* import { extractTime } from '@polkadot/util';
*
* const { days, minutes, hours, seconds, milliseconds } = extractTime(6000); // 0, 0, 10, 0, 0
* ```
*/
export default function extractTime (milliseconds?: number): Time {
if (!milliseconds) {
return ZERO;
} else if (milliseconds < 1000) {
return { ...ZERO, milliseconds };
}
const secs = milliseconds / 1000;
if (secs < 60) {
const seconds = Math.floor(secs);
return addTime({ ...ZERO, seconds }, extractTime(milliseconds - (seconds * 1000)));
}
const mins = secs / 60;
if (mins < 60) {
const minutes = Math.floor(mins);
return addTime({ ...ZERO, minutes }, extractTime(milliseconds - (minutes * 60 * 1000)));
}
const hrs = mins / 60;
if (hrs < 24) {
const hours = Math.floor(hrs);
return addTime({ ...ZERO, hours }, extractTime(milliseconds - (hours * HRS * 1000)));
}
const days = Math.floor(hrs / 24);
return addTime({ ...ZERO, days }, extractTime(milliseconds - (days * DAY * 1000)));
}
+1
View File
@@ -10,6 +10,7 @@ import './polyfill';
export { default as assert } from './assert';
export { default as detectPackage } from './detectPackage';
export { default as extractTime } from './extractTime';
export { default as logger } from './logger';
export { default as promisify } from './promisify';
@@ -26,7 +26,7 @@ describe('TextDecoder', (): void => {
});
it('polyfills with no exceptions (with TextDecoder)', (): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-var-requires,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
(global as any).TextDecoder = require('util').TextDecoder;
// eslint-disable-next-line @typescript-eslint/no-var-requires
@@ -26,7 +26,7 @@ describe('TextEncoder', (): void => {
});
it('polyfills with no exceptions (with TextEncoder)', (): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-var-requires,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
(global as any).TextEncoder = require('util').TextEncoder;
// eslint-disable-next-line @typescript-eslint/no-var-requires
+8
View File
@@ -40,3 +40,11 @@ export type BnList = {
0: BN;
1: BN;
} & BN[];
export interface Time {
days: number;
hours: number;
minutes: number;
seconds: number;
milliseconds: number;
}
+1234 -1270
View File
File diff suppressed because it is too large Load Diff