HDKey.decode constructor

HDKey.decode(
  1. String b58, {
  2. int? privVersion,
  3. int? pubVersion,
})

Decodes a base58 string into a HDPrivateKey or HDPublicKey. May throw InvalidBase58, InvalidBase58Checksum or InvalidHDKey. If privVersion or/and pubVersion is provided, it shall require that the version is equal to either one of these for a corresponsing private or public key or else it shall throw InvalidHDKeyVersion.

Implementation

factory HDKey.decode(String b58, { int? privVersion, int? pubVersion }) {

  final data = base58Decode(b58);
  if (data.length != encodedLength) throw InvalidHDKey();

  final keyType = data[45];
  final isPriv = keyType == 0;
  if (!isPriv && keyType != 2 && keyType != 3) throw InvalidHDKey();

  ByteData bd = data.buffer.asByteData();

  if (privVersion != null || pubVersion != null) {
    // Check version if either expected version is provided. Otherwise ignore.
    final version = bd.getUint32(0);
    // If expected version is only public, then reject private and vice versa.
    if (privVersion == null && isPriv) throw InvalidHDKey();
    if (pubVersion == null && !isPriv) throw InvalidHDKey();
    // Ensure version matches
    if (isPriv && version != privVersion) throw InvalidHDKeyVersion();
    if (!isPriv && version != pubVersion) throw InvalidHDKeyVersion();
  }

  final depth = data[4];
  final parentFingerprint = bd.getUint32(5);
  if (depth == 0 && parentFingerprint != 0) throw InvalidHDKey();

  final index = bd.getUint32(9);
  if (depth == 0 && index != 0) throw InvalidHDKey();

  final chaincode = data.sublist(13, 45);

  try {

    return isPriv
      ? HDPrivateKey(
        privateKey: ECPrivateKey(data.sublist(46)),
        chaincode: chaincode,
        depth: depth,
        index: index,
        parentFingerprint: parentFingerprint,
      )
      : HDPublicKey(
        publicKey: ECPublicKey(data.sublist(45)),
        chaincode: chaincode,
        depth: depth,
        index: index,
        parentFingerprint: parentFingerprint,
      );

  } on Exception {
    // If the key provided is invalid, an exception will have been thrown.
    throw InvalidHDKey();
  }

}