Skip to content

Latest commit

 

History

History
323 lines (236 loc) · 9.34 KB

File metadata and controls

323 lines (236 loc) · 9.34 KB

API Overview

Complete API reference for the BIP32/BIP39 library.

Package Structure

xyz.tcheeric.bips
├── bip32
│   ├── Bip32               # BIP32 hierarchical deterministic key derivation
│   └── nut
│       └── Nut13Derivation # NUT-13 Cashu deterministic secrets
└── bip39
    ├── Bip39               # High-level BIP39 API
    ├── MnemonicGenerator   # Generate mnemonic phrases
    ├── MnemonicValidator   # Validate mnemonic phrases
    ├── SeedCalculator      # Convert mnemonics to seeds
    └── WordList            # Multi-language wordlists

Quick Reference

BIP39 Operations

Operation Class Method
Generate mnemonic Bip39 generateMnemonic(int wordCount)
Validate mnemonic Bip39 isValidMnemonic(String mnemonic)
Mnemonic → Seed Bip39 mnemonicToSeed(String mnemonic, String passphrase)
Mnemonic → Master Key Bip39 mnemonicToMasterKey(String mnemonic, String passphrase)

BIP32 Operations

Operation Class Method
Derive master key Bip32 deriveMasterKey(byte[] seed)
Derive child key Bip32 deriveKey(DeterministicKey master, String path)
Get private key Bip32 getPrivateKeyBytes(DeterministicKey key)
Get public key Bip32 getPublicKeyBytes(DeterministicKey key, boolean compressed)
Get chain code Bip32 getChainCode(DeterministicKey key)

NUT-13 Operations

Operation Class Method
Derive secret Nut13Derivation deriveSecret(DeterministicKey master, String keysetId, int counter)
Derive blinding factor Nut13Derivation deriveBlindingFactor(DeterministicKey master, String keysetId, int counter)
Derive both Nut13Derivation deriveSecretAndBlindingFactor(...)
Convert keyset ID Nut13Derivation keysetIdToInt(String keysetIdHex)
Build path Nut13Derivation buildDerivationPath(int keysetId, int counter, boolean isBlindingFactor)

Core Classes

Bip39

High-level API for BIP39 operations.

// Generate random 12-word mnemonic
String mnemonic = Bip39.generateMnemonic(12);

// Validate
boolean valid = Bip39.isValidMnemonic(mnemonic);

// Convert to seed
byte[] seed = Bip39.mnemonicToSeed(mnemonic, "");

// Derive master key
DeterministicKey master = Bip39.mnemonicToMasterKey(mnemonic, "");

Key Methods:

  • generateMnemonic(int wordCount) - Generate random mnemonic
  • isValidMnemonic(String mnemonic) - Validate mnemonic
  • mnemonicToSeed(String mnemonic, String passphrase) - Convert to 64-byte seed
  • mnemonicToMasterKey(String mnemonic, String passphrase) - Derive BIP32 master key

Bip32

BIP32 hierarchical deterministic key derivation.

// Derive master key from seed
DeterministicKey master = Bip32.deriveMasterKey(seed);

// Derive child key
DeterministicKey child = Bip32.deriveKey(master, "m/44'/0'/0'/0/0");

// Extract key material
byte[] privateKey = Bip32.getPrivateKeyBytes(child);
byte[] publicKey = Bip32.getPublicKeyBytes(child, true);
byte[] chainCode = Bip32.getChainCode(child);

Key Methods:

  • deriveMasterKey(byte[] seed) - Create master key from seed
  • deriveKey(DeterministicKey master, String path) - Derive child using path
  • getPrivateKeyBytes(DeterministicKey key) - Get 32-byte private key
  • getPublicKeyBytes(DeterministicKey key, boolean compressed) - Get public key
  • parsePath(String path) - Parse BIP32 path string

Nut13Derivation

NUT-13 deterministic secret derivation for Cashu.

// Convert keyset ID
int keysetInt = Nut13Derivation.keysetIdToInt("009a1f293253e41e");

// Derive secret
byte[] secret = Nut13Derivation.deriveSecret(master, keysetId, counter);

// Derive blinding factor
byte[] blinding = Nut13Derivation.deriveBlindingFactor(master, keysetId, counter);

// Derive both
var both = Nut13Derivation.deriveSecretAndBlindingFactor(master, keysetId, counter);

Key Methods:

  • keysetIdToInt(String keysetIdHex) - Convert keyset ID to integer
  • deriveSecret(...) - Derive deterministic secret
  • deriveBlindingFactor(...) - Derive blinding factor
  • deriveSecretAndBlindingFactor(...) - Derive both in one call
  • buildDerivationPath(...) - Build NUT-13 BIP32 path

Derivation Path: m/129372'/0'/{keyset_id}'/{counter}'/{0|1}

Supporting Classes

WordList

Manages BIP39 wordlists for multiple languages.

// Get English wordlist (default)
WordList english = WordList.english();

// Other languages
WordList french = WordList.french();
WordList spanish = WordList.spanish();
WordList japanese = WordList.japanese();

// Use wordlist
String word = wordList.getWord(0);  // "abandon"
int index = wordList.getIndex("abandon");  // 0
boolean contains = wordList.contains("abandon");  // true

Supported Languages:

  • English (2048 words)
  • French (2048 words)
  • Spanish (2048 words)
  • Japanese (2048 words, uses ideographic space)

MnemonicGenerator

Generates BIP39 mnemonic phrases.

MnemonicGenerator generator = new MnemonicGenerator(WordList.english());

// Generate from random entropy
String mnemonic = generator.generateRandom(12);

// Generate from specific entropy
byte[] entropy = new byte[16];
String mnemonic = generator.generate(entropy);

// Generate from hex
String mnemonic = generator.generateFromHex("00000000000000000000000000000000");

MnemonicValidator

Validates BIP39 mnemonic phrases.

MnemonicValidator validator = new MnemonicValidator(WordList.english());

// Simple validation
boolean valid = validator.isValid(mnemonic);

// Detailed validation
ValidationResult result = validator.validate(mnemonic);
if (!result.isValid()) {
    System.out.println("Error: " + result.getErrorMessage());
}

// Validate or throw
validator.validateOrThrow(mnemonic);  // throws InvalidMnemonicException

SeedCalculator

Converts mnemonics to seeds using PBKDF2-HMAC-SHA512.

// From mnemonic string
byte[] seed = SeedCalculator.calculateSeed(mnemonic, "passphrase");

// From word list
List<String> words = Arrays.asList(mnemonic.split(" "));
byte[] seed = SeedCalculator.calculateSeed(words, "passphrase");

Data Types

DeterministicKey

From bitcoinj library, represents a BIP32 hierarchical deterministic key.

Key Methods:

  • hasPrivKey() - Check if key has private component
  • getPrivKeyBytes() - Get private key (32 bytes)
  • getPubKey() - Get public key (33 or 65 bytes)
  • getChainCode() - Get chain code (32 bytes)

ChildNumber

From bitcoinj library, represents a component in a BIP32 path.

ChildNumber hardened = new ChildNumber(44, true);   // 44'
ChildNumber normal = new ChildNumber(0, false);     // 0

Constants

NUT-13 Constants

Nut13Derivation.NUT13_PURPOSE          // 129372 (UTF-8 of 🥜)
Nut13Derivation.COIN_TYPE              // 0
Nut13Derivation.INDEX_SECRET           // 0
Nut13Derivation.INDEX_BLINDING_FACTOR  // 1

Error Handling

Common Exceptions

Exception Thrown By Cause
IllegalArgumentException Most methods Invalid input parameters
InvalidMnemonicException MnemonicValidator Invalid mnemonic phrase
IndexOutOfBoundsException WordList Invalid word index
RuntimeException Crypto operations SHA-256 not available

Example Error Handling

try {
    // Validate before using
    if (!Bip39.isValidMnemonic(mnemonic)) {
        throw new IllegalArgumentException("Invalid mnemonic");
    }

    byte[] seed = Bip39.mnemonicToSeed(mnemonic, "");
    DeterministicKey master = Bip32.deriveMasterKey(seed);

} catch (IllegalArgumentException e) {
    System.err.println("Invalid input: " + e.getMessage());
} catch (Exception e) {
    System.err.println("Unexpected error: " + e.getMessage());
}

Thread Safety

Thread-Safe Classes:

  • Bip39 - All static methods are thread-safe
  • Bip32 - All static methods are thread-safe
  • Nut13Derivation - All static methods are thread-safe
  • WordList - Immutable after construction

Not Thread-Safe:

  • DeterministicKey - Should not be shared between threads without synchronization

Performance Considerations

Expensive Operations

  1. PBKDF2 (Seed Calculation): ~100-500ms

    • Uses 2048 iterations of HMAC-SHA512
    • Cache seeds when possible
  2. Key Derivation: ~1-10ms per derivation

    • Depends on path depth
    • Use cached parent keys for repeated derivations
  3. Mnemonic Validation: ~1-5ms

    • Includes checksum verification
    • Relatively fast compared to PBKDF2

Optimization Tips

// ✅ Good: Derive master once, reuse for all children
DeterministicKey master = Bip39.mnemonicToMasterKey(mnemonic, "");
for (int i = 0; i < 100; i++) {
    DeterministicKey child = Bip32.deriveKey(master, "m/44'/0'/0'/0/" + i);
}

// ❌ Bad: Derives master key 100 times
for (int i = 0; i < 100; i++) {
    DeterministicKey child = Bip32.deriveKeyFromMnemonic(
        mnemonic, "", "m/44'/0'/0'/0/" + i
    );
}

Version Compatibility

  • Java: 21
  • bitcoinj-core: 0.17
  • Maven: 3.6+

Related Documentation