| 32 | }; |
| 33 | |
| 34 | bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch) |
| 35 | { |
| 36 | // Skip leading spaces. |
| 37 | while (*psz && isspace(*psz)) |
| 38 | psz++; |
| 39 | // Skip and count leading '1's. |
| 40 | int zeroes = 0; |
| 41 | int length = 0; |
| 42 | while (*psz == '1') { |
| 43 | zeroes++; |
| 44 | psz++; |
| 45 | } |
| 46 | // Allocate enough space in big-endian base256 representation. |
| 47 | int size = strlen(psz) * 733 /1000 + 1; // log(58) / log(256), rounded up. |
| 48 | std::vector<unsigned char> b256(size); |
| 49 | // Process the characters. |
| 50 | static_assert(sizeof(mapBase58)/sizeof(mapBase58[0]) == 256, "mapBase58.size() should be 256"); // guarantee not out of range |
| 51 | while (*psz && !isspace(*psz)) { |
| 52 | // Decode base58 character |
| 53 | int carry = mapBase58[(uint8_t)*psz]; |
| 54 | if (carry == -1) // Invalid b58 character |
| 55 | return false; |
| 56 | int i = 0; |
| 57 | for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); (carry != 0 || i < length) && (it != b256.rend()); ++it, ++i) { |
| 58 | carry += 58 * (*it); |
| 59 | *it = carry % 256; |
| 60 | carry /= 256; |
| 61 | } |
| 62 | assert(carry == 0); |
| 63 | length = i; |
| 64 | psz++; |
| 65 | } |
| 66 | // Skip trailing spaces. |
| 67 | while (isspace(*psz)) |
| 68 | psz++; |
| 69 | if (*psz != 0) |
| 70 | return false; |
| 71 | // Skip leading zeroes in b256. |
| 72 | std::vector<unsigned char>::iterator it = b256.begin() + (size - length); |
| 73 | while (it != b256.end() && *it == 0) |
| 74 | it++; |
| 75 | // Copy result into output vector. |
| 76 | vch.reserve(zeroes + (b256.end() - it)); |
| 77 | vch.assign(zeroes, 0x00); |
| 78 | while (it != b256.end()) |
| 79 | vch.push_back(*(it++)); |
| 80 | return true; |
| 81 | } |
| 82 | |
| 83 | std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend) |
| 84 | { |