Skip to content

Commit

Permalink
Polish DecodeBase58
Browse files Browse the repository at this point in the history
  • Loading branch information
Lőrinc committed Feb 26, 2024
1 parent 12dd336 commit 73845ec
Showing 1 changed file with 19 additions and 20 deletions.
39 changes: 19 additions & 20 deletions src/base58.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,46 +45,45 @@ static constexpr int ENCODE_GROUP_SIZE = 7; // Group bytes into longs, consideri

[[nodiscard]] static bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch, int max_ret_len)
{
// Skip leading spaces.
while (*psz && IsSpace(*psz))
psz++;
++psz;

// Skip and count leading '1's.
int zeroes = 0;
int length = 0;
while (*psz == '1') {
zeroes++;
if (zeroes > max_ret_len) return false;
psz++;
int leading = 0;
for (; *psz == '1'; ++psz) {
++leading;
if (leading > max_ret_len) return false;
}

int size = 1 + strlen(psz) * LOG_58_256_RATIO / BASE_SCALE;
std::vector<unsigned char> b256(size);

// Process the characters.
static_assert(std::size(MAP_BASE58) == 256, "MAP_BASE58.size() should be 256"); // guarantee not out of range
while (*psz && !IsSpace(*psz)) {
// Decode base58 character
int length = 0;
for (; *psz && !IsSpace(*psz); ++psz) {
int carry = MAP_BASE58[(uint8_t)*psz];
if (carry == -1) // Invalid b58 character
return false;
if (carry == -1) return false;

int i = 0;
for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); (carry != 0 || i < length) && (it != b256.rend()); ++it, ++i) {
for (auto it = b256.rbegin(); (carry != 0 || i < length) && (it != b256.rend()); ++it, ++i) {
carry += 58 * (*it);
*it = carry % 256;
carry /= 256;
}
assert(carry == 0);
length = i;
if (length + zeroes > max_ret_len) return false;
psz++;
if (length + leading > max_ret_len) return false;
}
// Skip trailing spaces.
while (IsSpace(*psz))
psz++;
++psz;
if (*psz != 0)
return false;
std::vector<unsigned char>::iterator it = b256.begin() + (size - length);

auto it = b256.begin() + (size - length);
// Copy result into output vector.
vch.reserve(zeroes + (b256.end() - it));
vch.assign(zeroes, 0x00);
vch.reserve(leading + (b256.end() - it));
vch.assign(leading, 0x00);
while (it != b256.end())
vch.push_back(*(it++));
return true;
Expand Down

0 comments on commit 73845ec

Please sign in to comment.