validateAddressByNetwork function
Checks if the address is valid by the following 4 steps:
- Verify that the address is not null.
- Verify that the address is 38 bytes long.
- Verify that it matches the network
- 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;
}