encodeKey method

  1. @override
String encodeKey(
  1. List<int> pubKey, [
  2. Map<String, dynamic> kwargs = const {}
])
override

Overrides the base class method to encode a public key as a P2PKH (Pay-to-Public-Key-Hash) address.

This method encodes a public key as a P2PKH address using Base58 encoding. It expects an optional map of keyword arguments with 'net_ver' specifying the network version bytes, 'base58_alph' for the Base58 alphabet, and 'pub_key_mode' for the public key mode. It validates the arguments, processes the public key as a Secp256k1 key, determines the public key mode (compressed or uncompressed), generates a hash160 of the public key, and encodes it as a P2PKH address using Base58.

Parameters:

  • pubKey: The public key to be encoded as a P2PKH address.
  • kwargs: Optional keyword arguments with 'net_ver' for the network version, 'base58_alph' for Base58 alphabet, and 'pub_key_mode' for the public key mode.

Returns: A String representing the Base58-encoded P2PKH address derived from the provided public key.

Implementation

@override
String encodeKey(List<int> pubKey, [Map<String, dynamic> kwargs = const {}]) {
  /// Validate network version, Base58 alphabet, and public key mode arguments.
  AddrKeyValidator.validateAddressArgs<List<int>>(kwargs, "net_ver");
  final List<int> netVerBytes = kwargs["net_ver"];
  final alphabet = kwargs["base58_alph"] ?? Base58Alphabets.bitcoin;
  if (alphabet is! Base58Alphabets) {
    throw const AddressConverterException("invalid base58 alphabet");
  }
  final pubKeyModes = kwargs["pub_key_mode"] ?? PubKeyModes.compressed;
  if (pubKeyModes is! PubKeyModes) {
    throw const AddressConverterException("invalid pub key mode");
  }

  /// Validate and process the public key as a Secp256k1 key.
  final publicKey = AddrKeyValidator.validateAndGetSecp256k1Key(pubKey);

  /// Determine the public key bytes based on the selected mode.
  final List<int> pubKeyBytes = pubKeyModes == PubKeyModes.compressed
      ? publicKey.compressed
      : publicKey.uncompressed;

  /// Calculate the hash160 of the public key.
  final hash160 = QuickCrypto.hash160(pubKeyBytes);

  /// Combine the network version and hash160 to form the address bytes.
  return Base58Encoder.checkEncode(
      List<int>.from([...netVerBytes, ...hash160]), alphabet);
}