isRootKey static method

(bool, Uint8List) isRootKey(
  1. String xPrivateKey,
  2. Cryptocurrency cryptocurrency, {
  3. bool isPublicKey = false,
})

Determines whether a given extended private or public key is a root key.

xPrivateKey is the extended private or public key to check. cryptocurrency is the cryptocurrency configuration. isPublicKey is a flag indicating whether the key is a public key (default is false).

Returns a tuple containing a boolean indicating whether the key is a root key and the key data as a Uint8List.

Implementation

static (bool, Uint8List) isRootKey(
    String xPrivateKey, Cryptocurrency cryptocurrency,
    {bool isPublicKey = false}) {
  /// Decode the extended key from base58 format.
  final dec = bs.decodeCheck(xPrivateKey);

  /// Check if the decoded key has the expected length (78 bytes).
  if (dec.length != 78) {
    throw ArgumentError("Invalid xPrivateKey");
  }

  /// Extract the first 4 bytes (semantic) of the decoded key.
  final semantic = dec.sublist(0, 4);

  /// Determine the key type based on whether it's a public or private key.
  final type = isPublicKey
      ? cryptocurrency.extendedPublicKey.getExtendedType(semantic)
      : cryptocurrency.extendedPrivateKey.getExtendedType(semantic);

  /// If the key type is null, it's invalid for the given network.
  if (type == null) {
    throw ArgumentError("Invalid network");
  }

  /// Get the expected network prefix for the key type.
  final networkPrefix = isPublicKey
      ? cryptocurrency.extendedPublicKey.getExtended(type)
      : cryptocurrency.extendedPrivateKey.getExtended(type);

  /// Create the expected prefix for network identification.
  final prefix = hexToBytes("${networkPrefix}000000000000000000");

  /// Check if the prefix of the decoded key matches the expected prefix.
  return (bytesListEqual(prefix, dec.sublist(0, prefix.length)), dec);
}