validateAddressByNetwork function

Map<String, dynamic> validateAddressByNetwork(
  1. String networkPrefix,
  2. String address
)

Checks if the address is valid by the following 4 steps:

  1. Verify that the address is not null.
  2. Verify that the address is 38 bytes long.
  3. Verify that it matches the network
  4. Verify that the hash matches the checksum The first argument is the prefix to validate against and the second argument is the address to run the validation on. Result object with whether or not the operation was successful and whether or not the address is valid for a given network

Implementation

Map<String, dynamic> validateAddressByNetwork(
    String networkPrefix, String address) {
// response on completion of the validation
  final result = <String, dynamic>{};
  result['success'] = false;
  if (!isValidNetwork(networkPrefix)) {
    result['errorMsg'] = 'Invalid network provided';
    return result;
  }

  if (address.isEmpty) {
    result['errorMsg'] = 'No addresses provided';
    return result;
  }

// get the decimal of the network prefix. It should always be a valid network prefix due to the first conditional, but the language constraint requires us to check if it is null first.
  final networkDecimal =
      (networksDefault[networkPrefix] ?? const {})['decimal'];

// run validation on the address

  final decodedAddress = Base58Encoder.instance.decode(address);

// validation: base58 38 byte obj that matches the networkPrefix hex value

  if (decodedAddress.length != addressLength ||
      decodedAddress.first != networkDecimal) {
    result['errorMsg'] = 'Invalid address for network: $networkPrefix';
    return result;
  } else {
    //address has correct length and matches the network, now validate the checksum
    if (!validChecksum(decodedAddress)) {
      result['errorMsg'] = 'Addresses with invalid checksums found';
      return result;
    }
  }

  result['success'] = true;

  return result;
}