decodeXAddress static method

XRPXAddressDecodeResult decodeXAddress(
  1. String addr,
  2. List<int>? prefix
)

Decodes an X-Address and extracts the address hash and, if present, the tag.

Implementation

static XRPXAddressDecodeResult decodeXAddress(
  String addr,
  List<int>? prefix,
) {
  final List<int> addrDecBytes = Base58Decoder.checkDecode(
    addr,
    Base58Alphabets.ripple,
  );

  AddrDecUtils.validateBytesLength(
    addrDecBytes,
    QuickCrypto.hash160DigestSize +
        _XRPAddressConst.xAddressPrefixLength +
        _XRPAddressConst.xAddressTagLength,
  );

  final prefixBytes = addrDecBytes.sublist(
    0,
    _XRPAddressConst.xAddressPrefixLength,
  );

  if (prefix != null) {
    if (!BytesUtils.bytesEqual(prefix, prefixBytes)) {
      throw AddressConverterException.addressValidationFailed(
        reason: "Invalid address checksum.",
      );
    }
  } else {
    if (!BytesUtils.bytesEqual(
          prefixBytes,
          _XRPAddressConst._xAddressPrefixMain,
        ) &&
        !BytesUtils.bytesEqual(
          prefixBytes,
          _XRPAddressConst._xAddressPrefixTest,
        )) {
      throw AddressConverterException.addressValidationFailed(
        reason: "Invalid address prefix.",
      );
    }
  }

  final List<int> addrHash = addrDecBytes.sublist(
    prefixBytes.length,
    QuickCrypto.hash160DigestSize + prefixBytes.length,
  );

  List<int> tagBytes = addrDecBytes.sublist(
    addrDecBytes.length - _XRPAddressConst.xAddressTagLength,
  );
  final int tagFlag = tagBytes[0];
  if (tagFlag != 0 && tagFlag != 1) {
    throw AddressConverterException.addressValidationFailed(
      reason: "Invalid address tag.",
    );
  }
  tagBytes = tagBytes.sublist(1);
  if (tagFlag == 0 && !BytesUtils.bytesEqual(tagBytes, List.filled(8, 0))) {
    throw AddressConverterException.addressValidationFailed(
      reason: "Invalid address tag.",
    );
  }

  int? tag;
  if (tagFlag == 1) {
    tag = BinaryOps.readUint32LE(tagBytes);
  }

  return XRPXAddressDecodeResult(
    bytes: addrHash,
    tag: tag,
    isTestnet: BytesUtils.bytesEqual(
      prefixBytes,
      _XRPAddressConst._xAddressPrefixTest,
    ),
  );
}