@polkadot/util-crypto#mnemonicValidate TypeScript Examples

The following examples show how to use @polkadot/util-crypto#mnemonicValidate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Create.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function updateAddress (seed: string, derivePath: string, seedType: SeedType, pairType: PairType): AddressState {
  let address: string | null = null;
  let deriveValidation: DeriveValidationOutput = deriveValidate(seed, seedType, derivePath, pairType);
  let isSeedValid = seedType === 'raw'
    ? rawValidate(seed)
    : mnemonicValidate(seed);

  if (!deriveValidation?.error && isSeedValid) {
    try {
      address = addressFromSeed(seed, derivePath, pairType);
    } catch (error) {
      console.error(error);
      deriveValidation = { error: (error as Error).message ? (error as Error).message : (error as Error).toString() };
      isSeedValid = false;
    }
  }

  return {
    address,
    derivePath,
    deriveValidation,
    isSeedValid,
    pairType,
    seed,
    seedType
  };
}
Example #2
Source File: keyring.ts    From sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Generate a set of new mnemonic.
 */
async function gen(mnemonic: string, ss58Format: number, cryptoType: KeypairType, derivePath: string) {
  const key = mnemonic || mnemonicGenerate();
  if (!mnemonicValidate(key)) return null;

  const keyPair = keyring.addFromMnemonic(key + (derivePath || ""), {}, cryptoType || "sr25519");
  const address = encodeAddress(keyPair.publicKey, ss58Format || 0);
  const icons = await account.genIcons([address]);
  return {
    mnemonic: key,
    address,
    svg: icons[0][1],
  };
}
Example #3
Source File: keyring.ts    From sdk with Apache License 2.0 5 votes vote down vote up
/**
 * mnemonic validate.
 */
async function checkMnemonicValid(mnemonic: string) {
  return mnemonicValidate(mnemonic);
}
Example #4
Source File: keyring.ts    From sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Import keyPair from mnemonic, rawSeed or keystore.
 */
function recover(keyType: string, cryptoType: KeypairType, key: string, password: string) {
  return new Promise((resolve, reject) => {
    let keyPair: KeyringPair;
    let mnemonic = "";
    let rawSeed = "";
    try {
      switch (keyType) {
        case "mnemonic":
          if (!mnemonicValidate(key.split("/")[0])) {
            throw new Error(`invalid mnemonic ${key}`);
          }
          keyPair = keyring.addFromMnemonic(key, {}, cryptoType);
          mnemonic = key;
          break;
        case "rawSeed":
          keyPair = keyring.addFromUri(key, {}, cryptoType);
          rawSeed = key;
          break;
        case "keystore":
          const keystore = JSON.parse(key);
          keyPair = keyring.addFromJson(keystore);
          try {
            keyPair.decodePkcs8(password);
          } catch (err) {
            resolve(null);
          }
          resolve({
            pubKey: u8aToHex(keyPair.publicKey),
            ...keyPair.toJson(password),
          });
          break;
      }
    } catch (err) {
      resolve({ error: err.message });
    }
    if (keyPair.address) {
      const json = keyPair.toJson(password);
      keyPair.lock();
      // try add to keyring again to avoid no encrypted data bug
      keyring.addFromJson(json);
      resolve({
        pubKey: u8aToHex(keyPair.publicKey),
        mnemonic,
        rawSeed,
        ...json,
      });
    } else {
      resolve(null);
    }
  });
}
Example #5
Source File: InjectKeys.tsx    From crust-apps with Apache License 2.0 4 votes vote down vote up
function InjectKeys ({ onClose }: Props): React.ReactElement<Props> | null {
  const { t } = useTranslation();
  const { queueRpc } = useContext(StatusContext);
  // this needs to align with what is set as the first value in `type`
  const [crypto, setCrypto] = useState<KeypairType>('sr25519');
  const [publicKey, setPublicKey] = useState(EMPTY_KEY);
  const [suri, setSuri] = useState('');
  const [keyType, setKeyType] = useState('babe');

  const keyTypeOptRef = useRef([
    { text: t<string>('Aura'), value: 'aura' },
    { text: t<string>('Babe'), value: 'babe' },
    { text: t<string>('Grandpa'), value: 'gran' },
    { text: t<string>('I\'m Online'), value: 'imon' },
    { text: t<string>('Parachains'), value: 'para' }
  ]);

  useEffect((): void => {
    setCrypto(CRYPTO_MAP[keyType][0]);
  }, [keyType]);

  useEffect((): void => {
    try {
      const { phrase } = keyExtractSuri(suri);

      assert(mnemonicValidate(phrase), 'Invalid mnemonic phrase');

      setPublicKey(u8aToHex(keyring.createFromUri(suri, {}, crypto).publicKey));
    } catch (error) {
      setPublicKey(EMPTY_KEY);
    }
  }, [crypto, suri]);

  const _onSubmit = useCallback(
    (): void => queueRpc({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
      rpc: { method: 'insertKey', section: 'author' } as any,
      values: [keyType, suri, publicKey]
    }),
    [keyType, publicKey, queueRpc, suri]
  );

  const _cryptoOptions = useMemo(
    () => CRYPTO_MAP[keyType].map((value): { text: string; value: KeypairType } => ({
      text: value === 'ed25519'
        ? t<string>('ed25519, Edwards')
        : t<string>('sr15519, Schnorrkel'),
      value
    })),
    [keyType, t]
  );

  return (
    <Modal
      header={t<string>('Inject Keys')}
      size='large'
    >
      <Modal.Content>
        <Modal.Columns hint={t<string>('The seed and derivation path will be submitted to the validator node. this is an advanced operation, only to be performed when you are sure of the security and connection risks.')}>
          <Input
            autoFocus
            isError={publicKey.length !== 66}
            label={t<string>('suri (seed & derivation)')}
            onChange={setSuri}
            value={suri}
          />
          <MarkWarning content={t<string>('This operation will submit the seed via an RPC call. Do not perform this operation on a public RPC node, but ensure that the node is local, connected to your validator and secure.')} />
        </Modal.Columns>
        <Modal.Columns hint={t<string>('The key type and crypto type to use for this key. Be aware that different keys have different crypto requirements. You should be familiar with the type requirements for the different keys.')}>
          <Dropdown
            label={t<string>('key type to set')}
            onChange={setKeyType}
            options={keyTypeOptRef.current}
            value={keyType}
          />
          <Dropdown
            isDisabled={_cryptoOptions.length === 1}
            label={t<string>('crypto type to use')}
            onChange={setCrypto}
            options={_cryptoOptions}
            value={crypto}
          />
        </Modal.Columns>
        <Modal.Columns hint={t<string>('This pubic key is what will be visible in your queued keys list. It is generated based on the seed and the crypto used.')}>
          <Input
            isDisabled
            label={t<string>('generated public key')}
            value={publicKey}
          />
        </Modal.Columns>
      </Modal.Content>
      <Modal.Actions onCancel={onClose}>
        <Button
          icon='sign-in-alt'
          label={t<string>('Submit key')}
          onClick={_onSubmit}
        />
      </Modal.Actions>
    </Modal>
  );
}