encode method

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

Encodes entropy bytes into an Electrum V2 mnemonic.

-entropyBytes: The entropy bytes to be encoded into an Electrum V2 mnemonic.

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 ArgumentException.invalidOperationArguments(
      "encode",
      name: "entropyBytes",
      reason: "Invalid entropy length",
    );
  }

  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 ArgumentException.invalidOperationArguments(
      "encode",
      name: "entropyBytes",
      reason: "Invalid entropy.",
    );
  }
  return mnemonicObj;
}