polkadot-js / common

Utilities and base libraries for use across polkadot-js for Polkadot and Substrate. Includes base libraries, crypto helpers and cross-environment helpers.
Apache License 2.0
250 stars 139 forks source link

Add support for bip39 with other wordlists #1804

Open jacogr opened 1 year ago

jacogr commented 1 year ago

We are pulling in the extra wordlists via https://github.com/polkadot-js/common/pull/1803

This has been PR-ed previously in https://github.com/polkadot-js/common/pull/1689 and there has been some discussion. However after giving it some thought, we could actually make this work.

part 1

  1. We need a wordlist option passed to the bip39 functions, e.g. last param of wordlist: string[] = DEFAULT_WORDLIST -

https://github.com/polkadot-js/common/blob/91a2eac220df188a5c339f2dcc6ca98e5896da0b/packages/util-crypto/src/mnemonic/bip39.ts#L53 https://github.com/polkadot-js/common/blob/91a2eac220df188a5c339f2dcc6ca98e5896da0b/packages/util-crypto/src/mnemonic/bip39.ts#L95

  1. We change the DEAFULT_WORDLIST usage in these functions so be wordlist instead.
  2. Add actual tests for these in bip39.spec.ts to ensure we are actually ok.

part 2

Now the base generation is ok, but we may still use the wasm versions which doesn't have support for this. To get around it -

  1. Adapt the wasm/js check inside the exposed functions to also take in a last param of wordlist?: string[], onlyJs?: boolean

https://github.com/polkadot-js/common/blob/91a2eac220df188a5c339f2dcc6ca98e5896da0b/packages/util-crypto/src/mnemonic/validate.ts#L22-L23 https://github.com/polkadot-js/common/blob/91a2eac220df188a5c339f2dcc6ca98e5896da0b/packages/util-crypto/src/mnemonic/toMiniSecret.ts#L11 https://github.com/polkadot-js/common/blob/91a2eac220df188a5c339f2dcc6ca98e5896da0b/packages/util-crypto/src/mnemonic/toLegacySeed.ts#L27 https://github.com/polkadot-js/common/blob/91a2eac220df188a5c339f2dcc6ca98e5896da0b/packages/util-crypto/src/mnemonic/toEntropy.ts#L9 https://github.com/polkadot-js/common/blob/91a2eac220df188a5c339f2dcc6ca98e5896da0b/packages/util-crypto/src/mnemonic/generate.ts#L21

  1. For these treat the wordlist the same as onlyJs, i.e. when passed in we want to take the JS (non-WASM) route, i.e. it ties into the changes we made in bip39.ts. This looks something like !hasBigInt || (!wordlist && !onlyJs && isReady()) and the param passed on the JS-only path
  2. For all the above add tests...

part 3

Now we also need keyring support -

  1. Make the required wordlist-in changes to addFromMnemonic, addFromUri & createFromUri in https://github.com/polkadot-js/common/blob/892004563faa65dcd81bf60cf8d2e5aba74ae9d4/packages/keyring/src/keyring.ts#L201-L223
  2. Add tests...
jacogr commented 1 year ago

1805 adds support for the first part above.

1814 adds support for the second part above.