More detailed error checking for base58 addresses

This commit is contained in:
Samuel Dobson
2021-10-01 12:14:48 +13:00
parent 1790a8ddac
commit 0b06e720c0
2 changed files with 27 additions and 11 deletions

View File

@@ -81,7 +81,11 @@ CTxDestination DecodeDestination(const std::string& str, const CChainParams& par
std::vector<unsigned char> data;
uint160 hash;
error_str = "";
if (DecodeBase58Check(str, data, 21)) {
// Note this will be false if it is a valid Bech32 address for a different network
bool is_bech32 = (ToLower(str.substr(0, params.Bech32HRP().size())) == params.Bech32HRP());
if (!is_bech32 && DecodeBase58Check(str, data, 21)) {
// base58-encoded Bitcoin addresses.
// Public-key-hash-addresses have version 0 (or 111 testnet).
// The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
@@ -98,15 +102,27 @@ CTxDestination DecodeDestination(const std::string& str, const CChainParams& par
return ScriptHash(hash);
}
// Set potential error message.
// This message may be changed if the address can also be interpreted as a Bech32 address.
error_str = "Invalid prefix for Base58-encoded address";
if (!std::equal(script_prefix.begin(), script_prefix.end(), data.begin()) &&
!std::equal(pubkey_prefix.begin(), pubkey_prefix.end(), data.begin())) {
error_str = "Invalid prefix for Base58-encoded address";
} else {
error_str = "Invalid length for Base58 address";
}
return CNoDestination();
} else if (!is_bech32) {
// Try Base58 decoding without the checksum, using a much larger max length
if (!DecodeBase58(str, data, 100)) {
error_str = "Invalid HRP or Base58 character in address";
} else {
error_str = "Invalid checksum or length of Base58 address";
}
return CNoDestination();
}
data.clear();
const auto dec = bech32::Decode(str);
if ((dec.encoding == bech32::Encoding::BECH32 || dec.encoding == bech32::Encoding::BECH32M) && dec.data.size() > 0) {
// Bech32 decoding
error_str = "";
if (dec.hrp != params.Bech32HRP()) {
error_str = "Invalid prefix for Bech32 address";
return CNoDestination();
@@ -168,8 +184,8 @@ CTxDestination DecodeDestination(const std::string& str, const CChainParams& par
}
}
// Set error message if address can't be interpreted as Base58 or Bech32.
if (error_str.empty()) error_str = "Invalid address format";
//TODO: locate Bech32 errors
error_str = "Error in Bech32 encoding";
return CNoDestination();
}