1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <util/strencodings.h>
7 #include <util/string.h>
8 
9 #include <tinyformat.h>
10 
11 #include <algorithm>
12 #include <cstdlib>
13 #include <cstring>
14 #include <errno.h>
15 #include <limits>
16 
17 static const std::string CHARS_ALPHA_NUM = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
18 
19 static const std::string SAFE_CHARS[] =
20 {
21     CHARS_ALPHA_NUM + " .,;-_/:?@()", // SAFE_CHARS_DEFAULT
22     CHARS_ALPHA_NUM + " .,;-_?@", // SAFE_CHARS_UA_COMMENT
23     CHARS_ALPHA_NUM + ".-_", // SAFE_CHARS_FILENAME
24     CHARS_ALPHA_NUM + "!*'();:@&=+$,/?#[]-_.~%", // SAFE_CHARS_URI
25 };
26 
SanitizeString(const std::string & str,int rule)27 std::string SanitizeString(const std::string& str, int rule)
28 {
29     std::string strResult;
30     for (std::string::size_type i = 0; i < str.size(); i++)
31     {
32         if (SAFE_CHARS[rule].find(str[i]) != std::string::npos)
33             strResult.push_back(str[i]);
34     }
35     return strResult;
36 }
37 
38 const signed char p_util_hexdigit[256] =
39 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
40   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
41   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
42   0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
43   -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
44   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
45   -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
46   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
47   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
48   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
49   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
50   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
51   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
52   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
53   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
54   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
55 
HexDigit(char c)56 signed char HexDigit(char c)
57 {
58     return p_util_hexdigit[(unsigned char)c];
59 }
60 
IsHex(const std::string & str)61 bool IsHex(const std::string& str)
62 {
63     for(std::string::const_iterator it(str.begin()); it != str.end(); ++it)
64     {
65         if (HexDigit(*it) < 0)
66             return false;
67     }
68     return (str.size() > 0) && (str.size()%2 == 0);
69 }
70 
IsHexNumber(const std::string & str)71 bool IsHexNumber(const std::string& str)
72 {
73     size_t starting_location = 0;
74     if (str.size() > 2 && *str.begin() == '0' && *(str.begin()+1) == 'x') {
75         starting_location = 2;
76     }
77     for (const char c : str.substr(starting_location)) {
78         if (HexDigit(c) < 0) return false;
79     }
80     // Return false for empty string or "0x".
81     return (str.size() > starting_location);
82 }
83 
ParseHex(const char * psz)84 std::vector<unsigned char> ParseHex(const char* psz)
85 {
86     // convert hex dump to vector
87     std::vector<unsigned char> vch;
88     while (true)
89     {
90         while (IsSpace(*psz))
91             psz++;
92         signed char c = HexDigit(*psz++);
93         if (c == (signed char)-1)
94             break;
95         unsigned char n = (c << 4);
96         c = HexDigit(*psz++);
97         if (c == (signed char)-1)
98             break;
99         n |= c;
100         vch.push_back(n);
101     }
102     return vch;
103 }
104 
ParseHex(const std::string & str)105 std::vector<unsigned char> ParseHex(const std::string& str)
106 {
107     return ParseHex(str.c_str());
108 }
109 
SplitHostPort(std::string in,uint16_t & portOut,std::string & hostOut)110 void SplitHostPort(std::string in, uint16_t& portOut, std::string& hostOut)
111 {
112     size_t colon = in.find_last_of(':');
113     // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
114     bool fHaveColon = colon != in.npos;
115     bool fBracketed = fHaveColon && (in[0] == '[' && in[colon - 1] == ']'); // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe
116     bool fMultiColon = fHaveColon && (in.find_last_of(':', colon - 1) != in.npos);
117     if (fHaveColon && (colon == 0 || fBracketed || !fMultiColon)) {
118         uint16_t n;
119         if (ParseUInt16(in.substr(colon + 1), &n)) {
120             in = in.substr(0, colon);
121             portOut = n;
122         }
123     }
124     if (in.size() > 0 && in[0] == '[' && in[in.size() - 1] == ']') {
125         hostOut = in.substr(1, in.size() - 2);
126     } else {
127         hostOut = in;
128     }
129 }
130 
EncodeBase64(Span<const unsigned char> input)131 std::string EncodeBase64(Span<const unsigned char> input)
132 {
133     static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
134 
135     std::string str;
136     str.reserve(((input.size() + 2) / 3) * 4);
137     ConvertBits<8, 6, true>([&](int v) { str += pbase64[v]; }, input.begin(), input.end());
138     while (str.size() % 4) str += '=';
139     return str;
140 }
141 
EncodeBase64(const std::string & str)142 std::string EncodeBase64(const std::string& str)
143 {
144     return EncodeBase64(MakeUCharSpan(str));
145 }
146 
DecodeBase64(const char * p,bool * pf_invalid)147 std::vector<unsigned char> DecodeBase64(const char* p, bool* pf_invalid)
148 {
149     static const int decode64_table[256] =
150     {
151         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
152         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
153         -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
154         -1, -1, -1, -1, -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
155         15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
156         29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
157         49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
158         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
159         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
160         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
161         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
162         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
163         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
164     };
165 
166     const char* e = p;
167     std::vector<uint8_t> val;
168     val.reserve(strlen(p));
169     while (*p != 0) {
170         int x = decode64_table[(unsigned char)*p];
171         if (x == -1) break;
172         val.push_back(x);
173         ++p;
174     }
175 
176     std::vector<unsigned char> ret;
177     ret.reserve((val.size() * 3) / 4);
178     bool valid = ConvertBits<6, 8, false>([&](unsigned char c) { ret.push_back(c); }, val.begin(), val.end());
179 
180     const char* q = p;
181     while (valid && *p != 0) {
182         if (*p != '=') {
183             valid = false;
184             break;
185         }
186         ++p;
187     }
188     valid = valid && (p - e) % 4 == 0 && p - q < 4;
189     if (pf_invalid) *pf_invalid = !valid;
190 
191     return ret;
192 }
193 
DecodeBase64(const std::string & str,bool * pf_invalid)194 std::string DecodeBase64(const std::string& str, bool* pf_invalid)
195 {
196     if (!ValidAsCString(str)) {
197         if (pf_invalid) {
198             *pf_invalid = true;
199         }
200         return {};
201     }
202     std::vector<unsigned char> vchRet = DecodeBase64(str.c_str(), pf_invalid);
203     return std::string((const char*)vchRet.data(), vchRet.size());
204 }
205 
EncodeBase32(Span<const unsigned char> input,bool pad)206 std::string EncodeBase32(Span<const unsigned char> input, bool pad)
207 {
208     static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
209 
210     std::string str;
211     str.reserve(((input.size() + 4) / 5) * 8);
212     ConvertBits<8, 5, true>([&](int v) { str += pbase32[v]; }, input.begin(), input.end());
213     if (pad) {
214         while (str.size() % 8) {
215             str += '=';
216         }
217     }
218     return str;
219 }
220 
EncodeBase32(const std::string & str,bool pad)221 std::string EncodeBase32(const std::string& str, bool pad)
222 {
223     return EncodeBase32(MakeUCharSpan(str), pad);
224 }
225 
DecodeBase32(const char * p,bool * pf_invalid)226 std::vector<unsigned char> DecodeBase32(const char* p, bool* pf_invalid)
227 {
228     static const int decode32_table[256] =
229     {
230         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
231         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
232         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
233         -1, -1, -1, -1, -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
234         15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1,  0,  1,  2,
235          3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
236         23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
237         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
238         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
239         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
240         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
241         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
242         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
243     };
244 
245     const char* e = p;
246     std::vector<uint8_t> val;
247     val.reserve(strlen(p));
248     while (*p != 0) {
249         int x = decode32_table[(unsigned char)*p];
250         if (x == -1) break;
251         val.push_back(x);
252         ++p;
253     }
254 
255     std::vector<unsigned char> ret;
256     ret.reserve((val.size() * 5) / 8);
257     bool valid = ConvertBits<5, 8, false>([&](unsigned char c) { ret.push_back(c); }, val.begin(), val.end());
258 
259     const char* q = p;
260     while (valid && *p != 0) {
261         if (*p != '=') {
262             valid = false;
263             break;
264         }
265         ++p;
266     }
267     valid = valid && (p - e) % 8 == 0 && p - q < 8;
268     if (pf_invalid) *pf_invalid = !valid;
269 
270     return ret;
271 }
272 
DecodeBase32(const std::string & str,bool * pf_invalid)273 std::string DecodeBase32(const std::string& str, bool* pf_invalid)
274 {
275     if (!ValidAsCString(str)) {
276         if (pf_invalid) {
277             *pf_invalid = true;
278         }
279         return {};
280     }
281     std::vector<unsigned char> vchRet = DecodeBase32(str.c_str(), pf_invalid);
282     return std::string((const char*)vchRet.data(), vchRet.size());
283 }
284 
ParsePrechecks(const std::string & str)285 [[nodiscard]] static bool ParsePrechecks(const std::string& str)
286 {
287     if (str.empty()) // No empty string allowed
288         return false;
289     if (str.size() >= 1 && (IsSpace(str[0]) || IsSpace(str[str.size()-1]))) // No padding allowed
290         return false;
291     if (!ValidAsCString(str)) // No embedded NUL characters allowed
292         return false;
293     return true;
294 }
295 
ParseInt32(const std::string & str,int32_t * out)296 bool ParseInt32(const std::string& str, int32_t *out)
297 {
298     if (!ParsePrechecks(str))
299         return false;
300     char *endp = nullptr;
301     errno = 0; // strtol will not set errno if valid
302     long int n = strtol(str.c_str(), &endp, 10);
303     if(out) *out = (int32_t)n;
304     // Note that strtol returns a *long int*, so even if strtol doesn't report an over/underflow
305     // we still have to check that the returned value is within the range of an *int32_t*. On 64-bit
306     // platforms the size of these types may be different.
307     return endp && *endp == 0 && !errno &&
308         n >= std::numeric_limits<int32_t>::min() &&
309         n <= std::numeric_limits<int32_t>::max();
310 }
311 
ParseInt64(const std::string & str,int64_t * out)312 bool ParseInt64(const std::string& str, int64_t *out)
313 {
314     if (!ParsePrechecks(str))
315         return false;
316     char *endp = nullptr;
317     errno = 0; // strtoll will not set errno if valid
318     long long int n = strtoll(str.c_str(), &endp, 10);
319     if(out) *out = (int64_t)n;
320     // Note that strtoll returns a *long long int*, so even if strtol doesn't report an over/underflow
321     // we still have to check that the returned value is within the range of an *int64_t*.
322     return endp && *endp == 0 && !errno &&
323         n >= std::numeric_limits<int64_t>::min() &&
324         n <= std::numeric_limits<int64_t>::max();
325 }
326 
ParseUInt8(const std::string & str,uint8_t * out)327 bool ParseUInt8(const std::string& str, uint8_t *out)
328 {
329     uint32_t u32;
330     if (!ParseUInt32(str, &u32) || u32 > std::numeric_limits<uint8_t>::max()) {
331         return false;
332     }
333     if (out != nullptr) {
334         *out = static_cast<uint8_t>(u32);
335     }
336     return true;
337 }
338 
ParseUInt16(const std::string & str,uint16_t * out)339 bool ParseUInt16(const std::string& str, uint16_t* out)
340 {
341     uint32_t u32;
342     if (!ParseUInt32(str, &u32) || u32 > std::numeric_limits<uint16_t>::max()) {
343         return false;
344     }
345     if (out != nullptr) {
346         *out = static_cast<uint16_t>(u32);
347     }
348     return true;
349 }
350 
ParseUInt32(const std::string & str,uint32_t * out)351 bool ParseUInt32(const std::string& str, uint32_t *out)
352 {
353     if (!ParsePrechecks(str))
354         return false;
355     if (str.size() >= 1 && str[0] == '-') // Reject negative values, unfortunately strtoul accepts these by default if they fit in the range
356         return false;
357     char *endp = nullptr;
358     errno = 0; // strtoul will not set errno if valid
359     unsigned long int n = strtoul(str.c_str(), &endp, 10);
360     if(out) *out = (uint32_t)n;
361     // Note that strtoul returns a *unsigned long int*, so even if it doesn't report an over/underflow
362     // we still have to check that the returned value is within the range of an *uint32_t*. On 64-bit
363     // platforms the size of these types may be different.
364     return endp && *endp == 0 && !errno &&
365         n <= std::numeric_limits<uint32_t>::max();
366 }
367 
ParseUInt64(const std::string & str,uint64_t * out)368 bool ParseUInt64(const std::string& str, uint64_t *out)
369 {
370     if (!ParsePrechecks(str))
371         return false;
372     if (str.size() >= 1 && str[0] == '-') // Reject negative values, unfortunately strtoull accepts these by default if they fit in the range
373         return false;
374     char *endp = nullptr;
375     errno = 0; // strtoull will not set errno if valid
376     unsigned long long int n = strtoull(str.c_str(), &endp, 10);
377     if(out) *out = (uint64_t)n;
378     // Note that strtoull returns a *unsigned long long int*, so even if it doesn't report an over/underflow
379     // we still have to check that the returned value is within the range of an *uint64_t*.
380     return endp && *endp == 0 && !errno &&
381         n <= std::numeric_limits<uint64_t>::max();
382 }
383 
384 
ParseDouble(const std::string & str,double * out)385 bool ParseDouble(const std::string& str, double *out)
386 {
387     if (!ParsePrechecks(str))
388         return false;
389     if (str.size() >= 2 && str[0] == '0' && str[1] == 'x') // No hexadecimal floats allowed
390         return false;
391     std::istringstream text(str);
392     text.imbue(std::locale::classic());
393     double result;
394     text >> result;
395     if(out) *out = result;
396     return text.eof() && !text.fail();
397 }
398 
FormatParagraph(const std::string & in,size_t width,size_t indent)399 std::string FormatParagraph(const std::string& in, size_t width, size_t indent)
400 {
401     std::stringstream out;
402     size_t ptr = 0;
403     size_t indented = 0;
404     while (ptr < in.size())
405     {
406         size_t lineend = in.find_first_of('\n', ptr);
407         if (lineend == std::string::npos) {
408             lineend = in.size();
409         }
410         const size_t linelen = lineend - ptr;
411         const size_t rem_width = width - indented;
412         if (linelen <= rem_width) {
413             out << in.substr(ptr, linelen + 1);
414             ptr = lineend + 1;
415             indented = 0;
416         } else {
417             size_t finalspace = in.find_last_of(" \n", ptr + rem_width);
418             if (finalspace == std::string::npos || finalspace < ptr) {
419                 // No place to break; just include the entire word and move on
420                 finalspace = in.find_first_of("\n ", ptr);
421                 if (finalspace == std::string::npos) {
422                     // End of the string, just add it and break
423                     out << in.substr(ptr);
424                     break;
425                 }
426             }
427             out << in.substr(ptr, finalspace - ptr) << "\n";
428             if (in[finalspace] == '\n') {
429                 indented = 0;
430             } else if (indent) {
431                 out << std::string(indent, ' ');
432                 indented = indent;
433             }
434             ptr = finalspace + 1;
435         }
436     }
437     return out.str();
438 }
439 
atoi64(const std::string & str)440 int64_t atoi64(const std::string& str)
441 {
442 #ifdef _MSC_VER
443     return _atoi64(str.c_str());
444 #else
445     return strtoll(str.c_str(), nullptr, 10);
446 #endif
447 }
448 
atoi(const std::string & str)449 int atoi(const std::string& str)
450 {
451     return atoi(str.c_str());
452 }
453 
454 /** Upper bound for mantissa.
455  * 10^18-1 is the largest arbitrary decimal that will fit in a signed 64-bit integer.
456  * Larger integers cannot consist of arbitrary combinations of 0-9:
457  *
458  *   999999999999999999  1^18-1
459  *  9223372036854775807  (1<<63)-1  (max int64_t)
460  *  9999999999999999999  1^19-1     (would overflow)
461  */
462 static const int64_t UPPER_BOUND = 1000000000000000000LL - 1LL;
463 
464 /** Helper function for ParseFixedPoint */
ProcessMantissaDigit(char ch,int64_t & mantissa,int & mantissa_tzeros)465 static inline bool ProcessMantissaDigit(char ch, int64_t &mantissa, int &mantissa_tzeros)
466 {
467     if(ch == '0')
468         ++mantissa_tzeros;
469     else {
470         for (int i=0; i<=mantissa_tzeros; ++i) {
471             if (mantissa > (UPPER_BOUND / 10LL))
472                 return false; /* overflow */
473             mantissa *= 10;
474         }
475         mantissa += ch - '0';
476         mantissa_tzeros = 0;
477     }
478     return true;
479 }
480 
ParseFixedPoint(const std::string & val,int decimals,int64_t * amount_out)481 bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out)
482 {
483     int64_t mantissa = 0;
484     int64_t exponent = 0;
485     int mantissa_tzeros = 0;
486     bool mantissa_sign = false;
487     bool exponent_sign = false;
488     int ptr = 0;
489     int end = val.size();
490     int point_ofs = 0;
491 
492     if (ptr < end && val[ptr] == '-') {
493         mantissa_sign = true;
494         ++ptr;
495     }
496     if (ptr < end)
497     {
498         if (val[ptr] == '0') {
499             /* pass single 0 */
500             ++ptr;
501         } else if (val[ptr] >= '1' && val[ptr] <= '9') {
502             while (ptr < end && IsDigit(val[ptr])) {
503                 if (!ProcessMantissaDigit(val[ptr], mantissa, mantissa_tzeros))
504                     return false; /* overflow */
505                 ++ptr;
506             }
507         } else return false; /* missing expected digit */
508     } else return false; /* empty string or loose '-' */
509     if (ptr < end && val[ptr] == '.')
510     {
511         ++ptr;
512         if (ptr < end && IsDigit(val[ptr]))
513         {
514             while (ptr < end && IsDigit(val[ptr])) {
515                 if (!ProcessMantissaDigit(val[ptr], mantissa, mantissa_tzeros))
516                     return false; /* overflow */
517                 ++ptr;
518                 ++point_ofs;
519             }
520         } else return false; /* missing expected digit */
521     }
522     if (ptr < end && (val[ptr] == 'e' || val[ptr] == 'E'))
523     {
524         ++ptr;
525         if (ptr < end && val[ptr] == '+')
526             ++ptr;
527         else if (ptr < end && val[ptr] == '-') {
528             exponent_sign = true;
529             ++ptr;
530         }
531         if (ptr < end && IsDigit(val[ptr])) {
532             while (ptr < end && IsDigit(val[ptr])) {
533                 if (exponent > (UPPER_BOUND / 10LL))
534                     return false; /* overflow */
535                 exponent = exponent * 10 + val[ptr] - '0';
536                 ++ptr;
537             }
538         } else return false; /* missing expected digit */
539     }
540     if (ptr != end)
541         return false; /* trailing garbage */
542 
543     /* finalize exponent */
544     if (exponent_sign)
545         exponent = -exponent;
546     exponent = exponent - point_ofs + mantissa_tzeros;
547 
548     /* finalize mantissa */
549     if (mantissa_sign)
550         mantissa = -mantissa;
551 
552     /* convert to one 64-bit fixed-point value */
553     exponent += decimals;
554     if (exponent < 0)
555         return false; /* cannot represent values smaller than 10^-decimals */
556     if (exponent >= 18)
557         return false; /* cannot represent values larger than or equal to 10^(18-decimals) */
558 
559     for (int i=0; i < exponent; ++i) {
560         if (mantissa > (UPPER_BOUND / 10LL) || mantissa < -(UPPER_BOUND / 10LL))
561             return false; /* overflow */
562         mantissa *= 10;
563     }
564     if (mantissa > UPPER_BOUND || mantissa < -UPPER_BOUND)
565         return false; /* overflow */
566 
567     if (amount_out)
568         *amount_out = mantissa;
569 
570     return true;
571 }
572 
ToLower(const std::string & str)573 std::string ToLower(const std::string& str)
574 {
575     std::string r;
576     for (auto ch : str) r += ToLower((unsigned char)ch);
577     return r;
578 }
579 
ToUpper(const std::string & str)580 std::string ToUpper(const std::string& str)
581 {
582     std::string r;
583     for (auto ch : str) r += ToUpper((unsigned char)ch);
584     return r;
585 }
586 
Capitalize(std::string str)587 std::string Capitalize(std::string str)
588 {
589     if (str.empty()) return str;
590     str[0] = ToUpper(str.front());
591     return str;
592 }
593 
HexStr(const Span<const uint8_t> s)594 std::string HexStr(const Span<const uint8_t> s)
595 {
596     std::string rv(s.size() * 2, '\0');
597     static constexpr char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
598                                          '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
599     auto it = rv.begin();
600     for (uint8_t v : s) {
601         *it++ = hexmap[v >> 4];
602         *it++ = hexmap[v & 15];
603     }
604     assert(it == rv.end());
605     return rv;
606 }
607