3.7 (#738)
* 3.7 * Update new rules * RegExp * formatBalance cleanups * Revert * Formatting * fill * format test fix * cleanups * Cleanups * Expand bip39 tests * Cleanups * Cleanups
This commit is contained in:
@@ -17,6 +17,25 @@ const LOOKUP = BASE32_ALPHABET
|
||||
return lookup;
|
||||
}, {});
|
||||
|
||||
/** @internal */
|
||||
function decode (output: Uint8Array, input: string, offset: number): [Uint8Array, number, number] {
|
||||
let bits = 0;
|
||||
let buffer = 0;
|
||||
let written = 0;
|
||||
|
||||
for (let i = offset; i < input.length; i++) {
|
||||
buffer = (buffer << BITS_PER_CHAR) | LOOKUP[input[i]];
|
||||
bits += BITS_PER_CHAR;
|
||||
|
||||
if (bits >= 8) {
|
||||
bits -= 8;
|
||||
output[written++] = 0xff & (buffer >> bits);
|
||||
}
|
||||
}
|
||||
|
||||
return [output, bits, buffer];
|
||||
}
|
||||
|
||||
/**
|
||||
* @name base32Decode
|
||||
* @summary Delookup a base32 value.
|
||||
@@ -26,22 +45,14 @@ const LOOKUP = BASE32_ALPHABET
|
||||
export default function base32Decode (value: string, ipfsCompat = false): Uint8Array {
|
||||
validate(value, ipfsCompat);
|
||||
|
||||
const out = new Uint8Array(((value.length - (ipfsCompat ? 1 : 0)) * BITS_PER_CHAR / 8) | 0);
|
||||
let bits = 0;
|
||||
let buffer = 0;
|
||||
let written = 0;
|
||||
|
||||
for (let i = (ipfsCompat ? 1 : 0); i < value.length; ++i) {
|
||||
buffer = (buffer << BITS_PER_CHAR) | LOOKUP[value[i]];
|
||||
bits += BITS_PER_CHAR;
|
||||
|
||||
if (bits >= 8) {
|
||||
bits -= 8;
|
||||
out[written++] = 0xff & (buffer >> bits);
|
||||
}
|
||||
}
|
||||
const offset = (ipfsCompat ? 1 : 0);
|
||||
const [output, bits, buffer] = decode(
|
||||
new Uint8Array(((value.length - offset) * BITS_PER_CHAR / 8) | 0),
|
||||
value,
|
||||
offset
|
||||
);
|
||||
|
||||
assert(!(bits >= BITS_PER_CHAR || 0xff & (buffer << (8 - bits))), 'Unexpected end of data');
|
||||
|
||||
return out;
|
||||
return output;
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -15,6 +15,7 @@
|
||||
|
||||
import createHash from 'create-hash';
|
||||
import { pbkdf2Sync } from 'pbkdf2';
|
||||
import { assert, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import randomAsU8a from '../random/asU8a';
|
||||
import DEFAULT_WORDLIST from './bip39-en';
|
||||
@@ -56,26 +57,20 @@ export function mnemonicToSeedSync (mnemonic: string, password?: string): Buffer
|
||||
return pbkdf2Sync(mnemonicBuffer, saltBuffer, 2048, 64, 'sha512');
|
||||
}
|
||||
|
||||
export function mnemonicToEntropy (mnemonic: string): string {
|
||||
export function mnemonicToEntropy (mnemonic: string): Uint8Array {
|
||||
const words = normalize(mnemonic).split(' ');
|
||||
|
||||
if (words.length % 3 !== 0) {
|
||||
throw new Error(INVALID_MNEMONIC);
|
||||
}
|
||||
assert(words.length % 3 === 0, INVALID_MNEMONIC);
|
||||
|
||||
// convert word indices to 11 bit binary strings
|
||||
const bits = words
|
||||
.map(
|
||||
(word: string): string => {
|
||||
const index = DEFAULT_WORDLIST.indexOf(word);
|
||||
.map((word): string => {
|
||||
const index = DEFAULT_WORDLIST.indexOf(word);
|
||||
|
||||
if (index === -1) {
|
||||
throw new Error(INVALID_MNEMONIC);
|
||||
}
|
||||
assert(index !== -1, INVALID_MNEMONIC);
|
||||
|
||||
return index.toString(2).padStart(11, '0');
|
||||
}
|
||||
)
|
||||
return index.toString(2).padStart(11, '0');
|
||||
})
|
||||
.join('');
|
||||
|
||||
// split the binary string into ENT/CS
|
||||
@@ -86,62 +81,34 @@ export function mnemonicToEntropy (mnemonic: string): string {
|
||||
// calculate the checksum and compare
|
||||
const entropyBytes = entropyBits.match(/(.{1,8})/g)?.map(binaryToByte);
|
||||
|
||||
if (!entropyBytes || entropyBytes.length < 16) {
|
||||
throw new Error(INVALID_ENTROPY);
|
||||
} else if (entropyBytes.length > 32) {
|
||||
throw new Error(INVALID_ENTROPY);
|
||||
} else if (entropyBytes.length % 4 !== 0) {
|
||||
throw new Error(INVALID_ENTROPY);
|
||||
}
|
||||
assert(entropyBytes && entropyBytes.length % 4 === 0 && entropyBytes.length >= 16 && entropyBytes.length <= 32, INVALID_ENTROPY);
|
||||
|
||||
const entropy = Buffer.from(entropyBytes);
|
||||
const entropy = u8aToU8a(entropyBytes);
|
||||
const newChecksum = deriveChecksumBits(entropy);
|
||||
|
||||
if (newChecksum !== checksumBits) {
|
||||
throw new Error(INVALID_CHECKSUM);
|
||||
}
|
||||
assert(newChecksum === checksumBits, INVALID_CHECKSUM);
|
||||
|
||||
return entropy.toString('hex');
|
||||
return entropy;
|
||||
}
|
||||
|
||||
export function entropyToMnemonic (entropy: Uint8Array): string {
|
||||
// 128 <= ENT <= 256
|
||||
if (entropy.length < 16) {
|
||||
throw new TypeError(INVALID_ENTROPY);
|
||||
}
|
||||
|
||||
if (entropy.length > 32) {
|
||||
throw new TypeError(INVALID_ENTROPY);
|
||||
} else if (entropy.length % 4 !== 0) {
|
||||
throw new TypeError(INVALID_ENTROPY);
|
||||
}
|
||||
assert(entropy.length % 4 === 0 && entropy.length >= 16 && entropy.length <= 32, INVALID_ENTROPY);
|
||||
|
||||
const entropyBits = bytesToBinary(Array.from(entropy));
|
||||
const checksumBits = deriveChecksumBits(entropy);
|
||||
|
||||
const bits = entropyBits + checksumBits;
|
||||
|
||||
// we just set it prior, so this is a safe check
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const chunks = bits.match(/(.{1,11})/g)!;
|
||||
|
||||
const words = chunks.map(
|
||||
(binary: string): string => {
|
||||
const index = binaryToByte(binary);
|
||||
|
||||
return DEFAULT_WORDLIST[index];
|
||||
}
|
||||
);
|
||||
|
||||
return words.join(' ');
|
||||
return (entropyBits + checksumBits).match(/(.{1,11})/g)!
|
||||
.map((binary) => DEFAULT_WORDLIST[binaryToByte(binary)])
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
export function generateMnemonic (strength?: number): string {
|
||||
strength = strength || 128;
|
||||
|
||||
if (strength % 32 !== 0) {
|
||||
throw new TypeError(INVALID_ENTROPY);
|
||||
}
|
||||
assert(strength % 32 === 0, INVALID_ENTROPY);
|
||||
|
||||
return entropyToMnemonic(randomAsU8a(strength / 8));
|
||||
}
|
||||
|
||||
@@ -11,24 +11,20 @@ describe('mnemonicGenerate', (): void => {
|
||||
});
|
||||
|
||||
it('generates a valid mnemonic (default strength)', (): void => {
|
||||
const mnemonic = generate();
|
||||
|
||||
console.error(mnemonic);
|
||||
|
||||
expect(
|
||||
validate(mnemonic)
|
||||
validate(generate())
|
||||
).toEqual(true);
|
||||
});
|
||||
|
||||
([12, 15, 18, 21, 24] as WordCount[]).forEach((num: WordCount): void => {
|
||||
it(`generates a valid mnemonic (${num} words)`, (): void => {
|
||||
const mnemonic = generate(num);
|
||||
const isValid = validate(mnemonic);
|
||||
[false, true].forEach((onlyJs): void => {
|
||||
const mnemonic = generate(num, onlyJs);
|
||||
const isValid = validate(mnemonic);
|
||||
|
||||
console.error(mnemonic);
|
||||
|
||||
expect(mnemonic.split(' ')).toHaveLength(num);
|
||||
expect(isValid).toEqual(true);
|
||||
expect(mnemonic.split(' ')).toHaveLength(num);
|
||||
expect(isValid).toEqual(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -30,8 +30,8 @@ const STRENGTH_MAP = {
|
||||
* const mnemonic = mnemonicGenerate(); // => string
|
||||
* ```
|
||||
*/
|
||||
export default function mnemonicGenerate (numWords: WordCount = 12): string {
|
||||
return isReady()
|
||||
export default function mnemonicGenerate (numWords: WordCount = 12, onlyJs = false): string {
|
||||
return isReady() && !onlyJs
|
||||
? bip39Generate(numWords)
|
||||
: generateMnemonic(STRENGTH_MAP[numWords]);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ describe('mnemonicToEntropy', (): void => {
|
||||
tests.forEach(([mnemonic, entropy], index): void => {
|
||||
it(`Created correct entropy for ${index}`, (): void => {
|
||||
expect(u8aToHex(toEntropy(mnemonic))).toEqual(entropy);
|
||||
expect(u8aToHex(toEntropy(mnemonic, true))).toEqual(entropy);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,17 +3,12 @@
|
||||
|
||||
import '../polyfill';
|
||||
|
||||
import { hexAddPrefix, hexToU8a } from '@polkadot/util';
|
||||
import { bip39ToEntropy, isReady } from '@polkadot/wasm-crypto';
|
||||
|
||||
import { mnemonicToEntropy } from './bip39';
|
||||
|
||||
export default function toEntropy (mnemonic: string): Uint8Array {
|
||||
return isReady()
|
||||
export default function toEntropy (mnemonic: string, onlyJs = false): Uint8Array {
|
||||
return isReady() && !onlyJs
|
||||
? bip39ToEntropy(mnemonic)
|
||||
: hexToU8a(
|
||||
hexAddPrefix(
|
||||
mnemonicToEntropy(mnemonic)
|
||||
)
|
||||
);
|
||||
: mnemonicToEntropy(mnemonic);
|
||||
}
|
||||
|
||||
@@ -6,22 +6,20 @@ import { waitReady } from '@polkadot/wasm-crypto';
|
||||
|
||||
import { mnemonicToLegacySeed } from './';
|
||||
|
||||
const MENMONIC = 'seed sock milk update focus rotate barely fade car face mechanic mercy';
|
||||
const SEED = '0x3c121e20de068083b49c2315697fb59a2d9e8643c24e5ea7628132c58969a027';
|
||||
|
||||
describe('mnemonicToLegacySeed', (): void => {
|
||||
beforeEach(async (): Promise<void> => {
|
||||
await waitReady();
|
||||
});
|
||||
|
||||
it('generates a valid seed', (): void => {
|
||||
expect(
|
||||
u8aToHex(
|
||||
mnemonicToLegacySeed('seed sock milk update focus rotate barely fade car face mechanic mercy')
|
||||
)
|
||||
).toEqual('0x3c121e20de068083b49c2315697fb59a2d9e8643c24e5ea7628132c58969a027');
|
||||
});
|
||||
|
||||
it('generates the seed via WASM', async (): Promise<void> => {
|
||||
await waitReady();
|
||||
|
||||
u8aToHex(mnemonicToLegacySeed(MENMONIC))
|
||||
).toEqual(SEED);
|
||||
expect(
|
||||
u8aToHex(
|
||||
mnemonicToLegacySeed('seed sock milk update focus rotate barely fade car face mechanic mercy')
|
||||
)
|
||||
).toEqual('0x3c121e20de068083b49c2315697fb59a2d9e8643c24e5ea7628132c58969a027');
|
||||
u8aToHex(mnemonicToLegacySeed(MENMONIC, undefined, true))
|
||||
).toEqual(SEED);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,8 +24,8 @@ import { mnemonicToSeedSync } from './bip39';
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export default function toLegacy (mnemonic: string, password = ''): Uint8Array {
|
||||
return isReady()
|
||||
export default function toLegacy (mnemonic: string, password = '', onlyJs = false): Uint8Array {
|
||||
return isReady() && !onlyJs
|
||||
? bip39ToSeed(mnemonic, password)
|
||||
: bufferToU8a(mnemonicToSeedSync(mnemonic, password)).subarray(0, 32);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,9 @@ import mnemonicToMiniSecret from './toMiniSecret';
|
||||
import tests from '../schnorrkel/keypair/testing';
|
||||
import { cryptoWaitReady } from '..';
|
||||
|
||||
const MNEMONIC = 'seed sock milk update focus rotate barely fade car face mechanic mercy';
|
||||
const SEED = '0x4d1ab2a57929edfd018aaa974e62ed557e3f54b4104acabedf73c8f5a1dbb029';
|
||||
|
||||
describe('mnemonicToMiniSecret', (): void => {
|
||||
beforeEach(async (): Promise<void> => {
|
||||
await cryptoWaitReady();
|
||||
@@ -14,8 +17,11 @@ describe('mnemonicToMiniSecret', (): void => {
|
||||
|
||||
it('generates a valid seed', (): void => {
|
||||
expect(
|
||||
u8aToHex(mnemonicToMiniSecret('seed sock milk update focus rotate barely fade car face mechanic mercy'))
|
||||
).toEqual('0x4d1ab2a57929edfd018aaa974e62ed557e3f54b4104acabedf73c8f5a1dbb029');
|
||||
u8aToHex(mnemonicToMiniSecret(MNEMONIC))
|
||||
).toEqual(SEED);
|
||||
expect(
|
||||
u8aToHex(mnemonicToMiniSecret(MNEMONIC, undefined, true))
|
||||
).toEqual(SEED);
|
||||
});
|
||||
|
||||
tests.forEach(([mnemonic, , seed], index): void => {
|
||||
@@ -26,6 +32,12 @@ describe('mnemonicToMiniSecret', (): void => {
|
||||
// mini returned here, only check first 32-bytes (64 hex + 2 prefix)
|
||||
seed.substr(0, 66)
|
||||
);
|
||||
expect(
|
||||
u8aToHex(mnemonicToMiniSecret(mnemonic, 'Substrate', true))
|
||||
).toEqual(
|
||||
// mini returned here, only check first 32-bytes (64 hex + 2 prefix)
|
||||
seed.substr(0, 66)
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,8 +9,8 @@ import { bip39ToMiniSecret, isReady } from '@polkadot/wasm-crypto';
|
||||
|
||||
import toEntropy from './toEntropy';
|
||||
|
||||
export default function toMiniSecret (mnemonic: string, password = ''): Uint8Array {
|
||||
if (isReady()) {
|
||||
export default function toMiniSecret (mnemonic: string, password = '', onlyJs = false): Uint8Array {
|
||||
if (isReady() && !onlyJs) {
|
||||
return bip39ToMiniSecret(mnemonic, password);
|
||||
}
|
||||
|
||||
|
||||
@@ -13,11 +13,17 @@ describe('mnemonicValidate', (): void => {
|
||||
expect(
|
||||
validate('seed sock milk update focus rotate barely fade car face mechanic mercy')
|
||||
).toEqual(true);
|
||||
expect(
|
||||
validate('seed sock milk update focus rotate barely fade car face mechanic mercy', true)
|
||||
).toEqual(true);
|
||||
});
|
||||
|
||||
it('returns false on invalid', (): void => {
|
||||
expect(
|
||||
validate('wine photo extra cushion basket dwarf humor cloud truck job boat submit')
|
||||
).toEqual(false);
|
||||
expect(
|
||||
validate('wine photo extra cushion basket dwarf humor cloud truck job boat submit', true)
|
||||
).toEqual(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -20,8 +20,8 @@ import { validateMnemonic } from './bip39';
|
||||
* const isValidMnemonic = mnemonicValidate(mnemonic); // => boolean
|
||||
* ```
|
||||
*/
|
||||
export default function mnemonicValidate (mnemonic: string): boolean {
|
||||
return isReady()
|
||||
export default function mnemonicValidate (mnemonic: string, onlyJs = false): boolean {
|
||||
return isReady() && !onlyJs
|
||||
? bip39Validate(mnemonic)
|
||||
: validateMnemonic(mnemonic);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user