Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Bip39 Mnemonic Php Laravel Package

furqansiddiqui/bip39-mnemonic-php

PHP implementation of BIP39 mnemonics for generating and validating seed phrases. Supports multiple wordlists/languages, entropy-to-mnemonic and mnemonic-to-seed conversion, checksum handling, and deterministic wallet seed derivation for crypto apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require furqansiddiqui/bip39-mnemonic-php
    

    Add to composer.json if not using Composer globally. Requires PHP 8.2.

  2. First Use Case: Generate a Mnemonic

    use FurqanSiddiqui\Bip39\Bip39;
    
    $bip39 = new Bip39();
    $mnemonic = $bip39->generateMnemonic(); // e.g., "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
    
  3. Validate a Mnemonic

    $isValid = $bip39->validateMnemonic($mnemonic); // true/false
    
  4. Convert Mnemonic to Seed (with \SensitiveParameter support)

    $seed = $bip39->mnemonicToSeed($mnemonic, new \SensitiveParameter('your-passphrase-here'));
    
  5. Check Wordlist The package includes the default BIP39 English wordlist. For custom wordlists:

    $customWordlist = $bip39->getWordlist('custom'); // Requires custom wordlist file.
    

Implementation Patterns

Core Workflows

  1. Mnemonic Generation

    • Use generateMnemonic() with optional entropy (default: 128-bit).
    • Example: Generate a 24-word mnemonic for higher security:
      $mnemonic = $bip39->generateMnemonic(256); // 24 words
      
  2. Seed Derivation with \SensitiveParameter

    • Always use a passphrase for additional security. Leverage \SensitiveParameter for sensitive data handling:
      $seed = $bip39->mnemonicToSeed($mnemonic, new \SensitiveParameter('user-provided-passphrase'));
      
    • Store the seed (not the mnemonic) in secure storage if needed.
  3. Validation

    • Validate user input or generated mnemonics:
      if (!$bip39->validateMnemonic($input)) {
          throw new \InvalidArgumentException("Invalid mnemonic");
      }
      
  4. Wordlist Management

    • Load custom wordlists (e.g., for non-English languages):
      $bip39->setWordlist('path/to/custom_wordlist.txt');
      $mnemonic = $bip39->generateMnemonic(); // Uses custom wordlist
      
  5. Integration with Cryptography

    • Combine with libraries like paragonie/random_compat for secure entropy or web3p/hdwallet for key derivation:
      use ParagonIE\ConstantTime\Binary\SecureRandom;
      $entropy = SecureRandom::generateBytes(32); // 256-bit entropy
      $mnemonic = $bip39->generateMnemonicFromEntropy($entropy);
      

Integration Tips

  1. Laravel Service Provider Bind the Bip39 class to the container for easy dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(Bip39::class, function () {
            return new Bip39();
        });
    }
    

    Usage in controllers:

    use FurqanSiddiqui\Bip39\Bip39;
    
    public function generateMnemonic(Bip39 $bip39)
    {
        return $bip39->generateMnemonic();
    }
    
  2. Form Request Validation Validate mnemonics in Laravel requests:

    use FurqanSiddiqui\Bip39\Bip39;
    
    public function rules()
    {
        return [
            'mnemonic' => ['required', function ($attribute, $value, $fail) {
                $bip39 = new Bip39();
                if (!$bip39->validateMnemonic($value)) {
                    $fail('The '.$attribute.' must be a valid BIP39 mnemonic.');
                }
            }],
        ];
    }
    
  3. Environment Configuration Store passphrases or wordlist paths in .env:

    BIP39_PASSPHRASE=default_passphrase
    BIP39_WORDLIST_PATH=path/to/custom_wordlist.txt
    

    Load them dynamically:

    $bip39 = new Bip39();
    $bip39->setPassphrase(config('bip39.passphrase'));
    $bip39->setWordlist(config('bip39.wordlist_path'));
    
  4. Testing with PHPUnit Mock the Bip39 class in PHPUnit:

    $mock = $this->createMock(Bip39::class);
    $mock->method('generateMnemonic')->willReturn('test mnemonic');
    $this->app->instance(Bip39::class, $mock);
    

Gotchas and Tips

Pitfalls

  1. Entropy vs. Word Count

    • 128-bit entropy → 12 words.
    • 192-bit entropy → 18 words.
    • 256-bit entropy → 24 words.
    • Mistake: Assuming generateMnemonic() defaults to 256-bit. It defaults to 128-bit (12 words). Always specify if higher security is needed.
  2. Passphrase Handling with \SensitiveParameter

    • Never hardcode passphrases in source. Use .env or user-provided input.
    • Warning: A forgotten passphrase cannot be recovered. Document this for users.
    • New: Use \SensitiveParameter to explicitly mark passphrases as sensitive:
      $seed = $bip39->mnemonicToSeed($mnemonic, new \SensitiveParameter($passphrase));
      
  3. Wordlist Case Sensitivity

    • The wordlist is case-sensitive. Ensure user input matches the exact case (e.g., "abandon" vs. "ABANDON").
  4. Seed Storage

    • The seed is sensitive data. Avoid logging or committing it to version control. Use Laravel's encrypt() or a secure vault:
      $encryptedSeed = encrypt($seed);
      
  5. Custom Wordlist Format

    • Custom wordlists must be one word per line, UTF-8 encoded, and 2048 words long (BIP39 standard). Invalid formats will throw exceptions.
  6. PHP 8.2 Compatibility

    • Ensure your Laravel application is updated to PHP 8.2 for full compatibility with this release.

Debugging

  1. Validation Errors

    • If validateMnemonic() returns false, check:
      • Word count (12/18/24 words).
      • Wordlist match (use getWordlist() to inspect).
      • Passphrase handling (if applicable).
  2. Seed Mismatches

    • If derived keys don’t match expected values:
      • Verify the passphrase is correct.
      • Ensure the wordlist is unchanged (custom wordlists may alter outputs).
      • Check for typos in the mnemonic.
  3. Performance

    • Seed derivation (mnemonicToSeed()) is CPU-intensive. Avoid calling it in loops or high-frequency operations. Cache seeds if possible.

Extension Points

  1. Custom Entropy Sources

    • Override entropy generation for specialized use cases:
      $customEntropy = bin2hex(random_bytes(32));
      $mnemonic = $bip39->generateMnemonicFromEntropy($customEntropy);
      
  2. Language Support

    • Add support for new languages by extending the wordlist:
      $bip39->setWordlist('path/to/spanish_wordlist.txt');
      
  3. BIP39 Extensions

    • Combine with BIP32/BIP44 for hierarchical deterministic wallets:
      use BitWasp\Bitcoin\Key\Factory\Factory;
      use BitWasp\Bitcoin\Crypto\Random\SecureRandom;
      
      $seed = $bip39->mnemonicToSeed($mnemonic, '');
      $masterKey = Factory::createMasterPrivateKey($seed, SecureRandom::getBytes(32));
      
  4. Laravel Artisan Commands

    • Create a command to generate mnemonics:
      // app/Console/Commands/GenerateMnemonic.php
      public function handle(Bip39 $bip39)
      {
          $mnemonic = $bip39->generateMnemonic(256);
          $this->info("Generated Mnemonic:\n".$mnemonic);
      }
      
    • Register the command in AppServiceProvider:
      $this->commands([
          Commands
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor