encode method

  1. @override
Mnemonic encode(
  1. List<int> entropyBytes
)
override

Encodes entropy bytes into an Electrum V2 mnemonic.

This method takes a List<int> of entropy bytes as input and encodes them into an Electrum V2 mnemonic. It ensures that the entropy bits are sufficient for generating a valid mnemonic, and that the resulting mnemonic is valid for the specified mnemonic type. The method performs the encoding by repeatedly dividing the entropy value by the number of words in the word list and adding the corresponding words to the mnemonic.

entropyBytes: The entropy bytes to be encoded into an Electrum V2 mnemonic. Returns an Electrum V2 mnemonic representing the encoded data.

Implementation

@override
Mnemonic encode(List<int> entropyBytes) {
  final entropyInt = BigintUtils.fromBytes(entropyBytes);

  /// Check if the entropy bits are sufficient for a valid mnemonic
  if (!ElectrumV2EntropyGenerator.areEntropyBitsEnough(entropyInt)) {
    throw const ArgumentException(
        'Entropy bit length is not enough for generating a valid mnemonic');
  }

  final n = BigInt.from(wordsList.length());
  final mnemonic = <String>[];
  BigInt tempEntropy = entropyInt;

  /// Generate the mnemonic words from the entropy bytes
  while (tempEntropy > BigInt.zero) {
    final wordIdx = tempEntropy % n;
    tempEntropy ~/= n;
    mnemonic.add(wordsList.getWordAtIdx(wordIdx.toInt()));
  }

  /// Create an Electrum V2 mnemonic object from the generated words
  final mnemonicObj = ElectrumV2Mnemonic.fromList(mnemonic);

  /// Check if the resulting mnemonic is valid for the specified mnemonic type
  if (!ElectrumV2MnemonicUtils.isValidMnemonic(mnemonicObj, mnemonicType)) {
    throw const ArgumentException(
        'Entropy bytes are not suitable for generating a valid mnemonic');
  }
  return mnemonicObj;
}