Wallet.derive constructor

Wallet.derive(
  1. List<String> mnemonic,
  2. NetworkInfo networkInfo, {
  3. String lastDerivationPathSegment = '0',
})

Derives the private key from the given mnemonic using the specified networkInfo. Optionally can define a different derivation path setting lastDerivationPathSegment.

Implementation

factory Wallet.derive(
  List<String> mnemonic,
  NetworkInfo networkInfo, {
  String lastDerivationPathSegment = '0',
}) {
  // Get the mnemonic as a string
  final mnemonicString = mnemonic.join(' ');
  if (!Bip39.validateMnemonic(mnemonicString)) {
    throw Exception('Invalid mnemonic ' + mnemonicString);
  }

  final _lastDerivationPathSegmentCheck =
      int.tryParse(lastDerivationPathSegment) ?? -1;
  if (_lastDerivationPathSegmentCheck < 0) {
    throw Exception('Invalid index format $lastDerivationPathSegment');
  }

  // Convert the mnemonic to a BIP32 instance
  final seed = Bip39.mnemonicToSeed(mnemonicString);
  final root = Bip32.fromSeed(seed);

  // Get the node from the derivation path
  final derivedNode =
      root.derivePath('$BASE_DERIVATION_PATH/$lastDerivationPathSegment');

  // Get the curve data
  final secp256k1 = ECCSecp256k1();
  final point = secp256k1.G;

  // Compute the curve point associated to the private key
  final bigInt = BigInt.parse(hex.encode(derivedNode.privateKey!), radix: 16);
  final curvePoint = point * bigInt;

  // Get the public key
  final publicKeyBytes = curvePoint!.getEncoded();

  // Get the address
  final sha256Digest = SHA256Digest().process(publicKeyBytes);
  final address = RIPEMD160Digest().process(sha256Digest);

  // Return the key bytes
  return Wallet(
    address: address,
    publicKey: publicKeyBytes,
    privateKey: derivedNode.privateKey!,
    networkInfo: networkInfo,
  );
}