UNPKG

1.34 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import { hasBigInt } from '@polkadot/util';
4import { bip39ToSeed, isReady } from '@polkadot/wasm-crypto';
5import { mnemonicToSeedSync } from "./bip39.js";
6import { mnemonicValidate } from "./validate.js";
7/**
8 * @name mnemonicToLegacySeed
9 * @summary Creates a valid Ethereum/Bitcoin-compatible seed from a mnemonic input
10 * @example
11 * <BR>
12 *
13 * ```javascript
14 * import { mnemonicGenerate, mnemonicToLegacySeed, mnemonicValidate } from '@polkadot/util-crypto';
15 *
16 * const mnemonic = mnemonicGenerate(); // => string
17 * const isValidMnemonic = mnemonicValidate(mnemonic); // => boolean
18 *
19 * if (isValidMnemonic) {
20 * console.log(`Seed generated from mnemonic: ${mnemonicToLegacySeed(mnemonic)}`); => u8a
21 * }
22 * ```
23 */
24
25export function mnemonicToLegacySeed(mnemonic, password = '', onlyJs, byteLength = 32) {
26 if (!mnemonicValidate(mnemonic)) {
27 throw new Error('Invalid bip39 mnemonic specified');
28 } else if (![32, 64].includes(byteLength)) {
29 throw new Error(`Invalid seed length ${byteLength}, expected 32 or 64`);
30 }
31
32 return byteLength === 32 ? !hasBigInt || !onlyJs && isReady() ? bip39ToSeed(mnemonic, password) : mnemonicToSeedSync(mnemonic, password).subarray(0, 32) : mnemonicToSeedSync(mnemonic, password);
33}
\No newline at end of file