bip39

repository·master·Indexed 22 days ago

https://github.com/bitcoinjs/bip39

A JavaScript implementation of the Bitcoin BIP39 standard for generating deterministic keys from mnemonic phrases. Version 3.1.0 provides utilities to generate mnemonics from random entropy, convert between entropy and mnemonic phrases, validate mnemonics, and derive binary seeds using PBKDF2 with HMAC-SHA512. It includes support for multiple language wordlists and provides both synchronous and asynchronous API methods.

Tokens
3.8K
Snippets
19
Records
21
Agent score
77%

What's inside bip39

  1. Best practices for mnemonic recovery

    master

    When building applications that handle mnemonic phrases, it is recommended to allow recovery from phrases that have invalid checksums or use wordlists your app doesn't natively support.

    If a checksum is invalid, warn the user that the phrase was not generated by your app and ask if they want to proceed. This allows users to recover phrases from other apps. You should still perform basic validation, such as ensuring the input contains at least 12 words separated by spaces: phrase.trim().split(/\s+/g).length >= 12.

  2. Exclude wordlists from Webpack or Browserify bundles

    master

    To reduce bundle size in browser environments, you can exclude specific wordlists.

    Browserify: Use the --exclude flag for each JSON file you wish to remove.

    Webpack 5: Use the IgnorePlugin with a checkResource function to filter out unwanted wordlists via regex.

    # Browserify example
    $ browserify -r bip39 -s bip39 \
      --exclude=./wordlists/english.json \
      --exclude=./wordlists/japanese.json \
      > bip39.browser.js
    // Webpack 5 example (excluding all non-English wordlists)
    new webpack.IgnorePlugin({
      checkResource(resource) {
        return /.*\/wordlists\/(?!english).*\.json/.test(resource)
      }
    })
  3. Manage wordlists and default language

    master

    The library includes various wordlists. You can access them via bip39.wordlists[name]. You can change the default wordlist used for all subsequent calls (that don't explicitly specify one) using setDefaultWordlist(name).

    // Change default wordlist to italian
    bip39.setDefaultWordlist('italian')
    
    // Now entropyToMnemonic uses the italian wordlist
    bip39.entropyToMnemonic('00000000000000000000000000000fff')
    // => 'abaco abaco abaco abaco abaco abaco abaco abaco abaco aforisma zibetto'
  4. Generate a random mnemonic

    master

    Use generateMnemonic() to create a new random mnemonic phrase. By default, it uses 128 bits of entropy and the English wordlist.

    const mnemonic = bip39.generateMnemonic()
    // => 'seed sock milk update focus rotate barely fade car face mechanic mercy'
  5. Convert entropy to mnemonic and vice versa

    master

    Use entropyToMnemonic() to generate a mnemonic from a hex entropy string. Use mnemonicToEntropy() to perform the reverse operation.

    // Entropy to Mnemonic (defaults to English)
    const mnemonic = bip39.entropyToMnemonic('00000000000000000000000000000000')
    // => 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'
    
    // Mnemonic to Entropy
    bip39.mnemonicToEntropy(mnemonic)
    // => '00000000000000000000000000000000'
  6. Validate a mnemonic phrase

    master

    Use validateMnemonic() to check if a given mnemonic phrase is valid according to the BIP39 standard.

    bip39.validateMnemonic(mnemonic) // returns true
    bip39.validateMnemonic('basket actual') // returns false
  7. Convert mnemonic to seed

    master

    You can convert a mnemonic phrase into a seed (Buffer) using either the asynchronous mnemonicToSeed() method or the synchronous mnemonicToSeedSync() method. The synchronous version is less performance-oriented. You can optionally provide a password as a second argument.

    // Asynchronous version
    bip39.mnemonicToSeed('basket actual').then(bytes => {
      console.log(bytes.toString('hex'))
    })
    
    // Synchronous version
    bip39.mnemonicToSeedSync('basket actual', 'a password')
    // => <Buffer ...>
  8. Convert a mnemonic to entropy with mnemonicToEntropy()

    master

    Converts a BIP39 mnemonic phrase back into its original entropy (as a hex string).

    • mnemonic: The mnemonic phrase string.
    • wordlist: An array of 2048 words. If not provided, the default wordlist is used.

    Throws errors if the mnemonic is invalid, the checksum is incorrect, or the entropy length is out of bounds (16-32 bytes).

    const bip39 = require('bip39');
    
    const mnemonic = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about';
    const entropyHex = bip39.mnemonicToEntropy(mnemonic);
  9. Access wordlists and default settings

    master

    The library provides access to the available wordlists and the current default settings.

    • wordlists: An object containing all supported language wordlists.
    • getDefaultWordlist(): Returns the language key (e.g., 'EN') of the currently set default wordlist. Throws an error if no default is set.
    const bip39 = require('bip39');
    
    // Get all available wordlists
    const allWordlists = bip39.wordlists;
    
    // Get the current default language key
    const currentLang = bip39.getDefaultWordlist();
  10. Manage default wordlists with setDefaultWordlist()

    master

    Sets the global default wordlist used by generateMnemonic, entropyToMnemonic, mnemonicToEntropy, and validateMnemonic when no explicit wordlist is provided.

    • language: A string representing the language key (e.g., 'EN', 'JA', etc.) available in the wordlists object.

    Throws an error if the language is not found.

    const bip39 = require('bip39');
    
    try {
      bip39.setDefaultWordlist('EN');
    } catch (e) {
      console.error(e.message);
    }
  11. Derive a seed from a mnemonic phrase

    master

    Use these functions to derive a 512-bit seed from a mnemonic phrase using PBKDF2 with SHA-512.

    Synchronous derivation

    mnemonicToSeedSync(mnemonic, password?) returns a Buffer immediately.

    Asynchronous derivation

    mnemonicToSeed(mnemonic, password?) returns a Promise<Buffer>.

    • mnemonic: The mnemonic phrase string.
    • password: An optional passphrase used as additional salt. If provided, it is normalized and combined with the string 'mnemonic' to form the salt.
    // Sync
    const seed = mnemonicToSeedSync('word1 word2 ...', 'my-password');
    
    // Async
    const seedPromise = mnemonicToSeed('word1 word2 ...', 'my-password');
    const seed = await seedPromise;