Bitcoin ABC 0.34.2
P2P Digital Currency
strencodings.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2016 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 <crypto/hex_base.h>
12#include <span.h>
13
14#include <array>
15#include <cstdlib>
16#include <cstring>
17#include <optional>
18
19static const std::string CHARS_ALPHA_NUM =
20 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
21
22static const std::string SAFE_CHARS[] = {
23 // SAFE_CHARS_DEFAULT
24 CHARS_ALPHA_NUM + " .,;-_/:?@()",
25 // SAFE_CHARS_UA_COMMENT
26 CHARS_ALPHA_NUM + " .,;-_?@",
27 // SAFE_CHARS_FILENAME
28 CHARS_ALPHA_NUM + ".-_",
29 // SAFE_CHARS_URI
30 CHARS_ALPHA_NUM + "!*'();:@&=+$,/?#[]-_.~%",
31};
32
33std::string SanitizeString(std::string_view str, int rule) {
34 std::string result;
35 for (char c : str) {
36 if (SAFE_CHARS[rule].find(c) != std::string::npos) {
37 result.push_back(c);
38 }
39 }
40 return result;
41}
42
43bool IsHex(std::string_view str) {
44 for (char c : str) {
45 if (HexDigit(c) < 0) {
46 return false;
47 }
48 }
49 return (str.size() > 0) && (str.size() % 2 == 0);
50}
51
52template <typename Byte>
53std::optional<std::vector<Byte>> TryParseHex(std::string_view str) {
54 std::vector<Byte> vch;
55 auto it = str.begin();
56 while (it != str.end()) {
57 if (IsSpace(*it)) {
58 ++it;
59 continue;
60 }
61 auto c1 = HexDigit(*(it++));
62 if (it == str.end()) {
63 return std::nullopt;
64 }
65 auto c2 = HexDigit(*(it++));
66 if (c1 < 0 || c2 < 0) {
67 return std::nullopt;
68 }
69 vch.push_back(Byte(c1 << 4) | Byte(c2));
70 }
71 return vch;
72}
73template std::vector<std::byte> ParseHex(std::string_view);
74template std::vector<uint8_t> ParseHex(std::string_view);
75
76bool SplitHostPort(std::string_view in, uint16_t &portOut,
77 std::string &hostOut) {
78 bool valid = false;
79 size_t colon = in.find_last_of(':');
80 // if a : is found, and it either follows a [...], or no other : is in the
81 // string, treat it as port separator
82 bool fHaveColon = colon != in.npos;
83 // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is
84 // safe
85 bool fBracketed = fHaveColon && (in[0] == '[' && in[colon - 1] == ']');
86 bool fMultiColon =
87 fHaveColon && (in.find_last_of(':', colon - 1) != in.npos);
88 if (fHaveColon && (colon == 0 || fBracketed || !fMultiColon)) {
89 uint16_t n;
90 if (ParseUInt16(in.substr(colon + 1), &n)) {
91 in = in.substr(0, colon);
92 portOut = n;
93 valid = (portOut != 0);
94 }
95 } else {
96 valid = true;
97 }
98 if (in.size() > 0 && in[0] == '[' && in[in.size() - 1] == ']') {
99 hostOut = in.substr(1, in.size() - 2);
100 } else {
101 hostOut = in;
102 }
103
104 return valid;
105}
106
108 static const char *pbase64 =
109 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
110
111 std::string str;
112 str.reserve(((input.size() + 2) / 3) * 4);
113 ConvertBits<8, 6, true>([&](int v) { str += pbase64[v]; }, input.begin(),
114 input.end());
115 while (str.size() % 4) {
116 str += '=';
117 }
118 return str;
119}
120
121std::optional<std::vector<uint8_t>> DecodeBase64(std::string_view str) {
122 static const int8_t decode64_table[256] = {
123 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
124 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
125 -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57,
126 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6,
127 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
128 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
129 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1,
130 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
131 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
132 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
133 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
134 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
135 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
136 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
137 -1, -1, -1, -1};
138
139 if (str.size() % 4 != 0) {
140 return {};
141 }
142 /* One or two = characters at the end are permitted. */
143 if (str.size() >= 1 && str.back() == '=') {
144 str.remove_suffix(1);
145 }
146 if (str.size() >= 1 && str.back() == '=') {
147 str.remove_suffix(1);
148 }
149
150 std::vector<uint8_t> ret;
151 ret.reserve((str.size() * 3) / 4);
152 bool valid = ConvertBits<6, 8, false>(
153 [&](uint8_t c) { ret.push_back(c); }, str.begin(), str.end(),
154 [](char c) { return decode64_table[uint8_t(c)]; });
155 if (!valid) {
156 return {};
157 }
158
159 return ret;
160}
161
162std::string EncodeBase32(Span<const uint8_t> input, bool pad) {
163 static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
164
165 std::string str;
166 str.reserve(((input.size() + 4) / 5) * 8);
167 ConvertBits<8, 5, true>([&](int v) { str += pbase32[v]; }, input.begin(),
168 input.end());
169 if (pad) {
170 while (str.size() % 8) {
171 str += '=';
172 }
173 }
174 return str;
175}
176
177std::string EncodeBase32(std::string_view str, bool pad) {
178 return EncodeBase32(MakeUCharSpan(str), pad);
179}
180
181std::optional<std::vector<uint8_t>> DecodeBase32(std::string_view str) {
182 static const int8_t decode32_table[256] = {
183 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
184 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
185 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29,
186 30, 31, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6,
187 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
188 25, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
189 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1,
190 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
191 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
192 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
193 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
194 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
195 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
196 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
197 -1, -1, -1, -1};
198
199 if (str.size() % 8 != 0) {
200 return {};
201 }
202 /* 1, 3, 4, or 6 padding '=' suffix characters are permitted. */
203 if (str.size() >= 1 && str.back() == '=') {
204 str.remove_suffix(1);
205 }
206 if (str.size() >= 2 && str.substr(str.size() - 2) == "==") {
207 str.remove_suffix(2);
208 }
209 if (str.size() >= 1 && str.back() == '=') {
210 str.remove_suffix(1);
211 }
212 if (str.size() >= 2 && str.substr(str.size() - 2) == "==") {
213 str.remove_suffix(2);
214 }
215
216 std::vector<uint8_t> ret;
217 ret.reserve((str.size() * 5) / 8);
218 bool valid = ConvertBits<5, 8, false>(
219 [&](uint8_t c) { ret.push_back(c); }, str.begin(), str.end(),
220 [](char c) { return decode32_table[uint8_t(c)]; });
221
222 if (!valid) {
223 return {};
224 }
225
226 return ret;
227}
228
229namespace {
230template <typename T> bool ParseIntegral(std::string_view str, T *out) {
231 static_assert(std::is_integral<T>::value);
232 // Replicate the exact behavior of strtol/strtoll/strtoul/strtoull when
233 // handling leading +/- for backwards compatibility.
234 if (str.length() >= 2 && str[0] == '+' && str[1] == '-') {
235 return false;
236 }
237 const std::optional<T> opt_int =
238 ToIntegral<T>((!str.empty() && str[0] == '+') ? str.substr(1) : str);
239 if (!opt_int) {
240 return false;
241 }
242 if (out != nullptr) {
243 *out = *opt_int;
244 }
245 return true;
246}
247}; // namespace
248
249bool ParseInt32(std::string_view str, int32_t *out) {
250 return ParseIntegral<int32_t>(str, out);
251}
252
253bool ParseInt64(std::string_view str, int64_t *out) {
254 return ParseIntegral<int64_t>(str, out);
255}
256
257bool ParseUInt8(std::string_view str, uint8_t *out) {
258 return ParseIntegral<uint8_t>(str, out);
259}
260
261bool ParseUInt16(std::string_view str, uint16_t *out) {
262 return ParseIntegral<uint16_t>(str, out);
263}
264
265bool ParseUInt32(std::string_view str, uint32_t *out) {
266 return ParseIntegral<uint32_t>(str, out);
267}
268
269bool ParseUInt64(std::string_view str, uint64_t *out) {
270 return ParseIntegral<uint64_t>(str, out);
271}
272
273std::string FormatParagraph(std::string_view in, size_t width, size_t indent) {
274 std::stringstream out;
275 size_t ptr = 0;
276 size_t indented = 0;
277 while (ptr < in.size()) {
278 size_t lineend = in.find_first_of('\n', ptr);
279 if (lineend == std::string::npos) {
280 lineend = in.size();
281 }
282 const size_t linelen = lineend - ptr;
283 const size_t rem_width = width - indented;
284 if (linelen <= rem_width) {
285 out << in.substr(ptr, linelen + 1);
286 ptr = lineend + 1;
287 indented = 0;
288 } else {
289 size_t finalspace = in.find_last_of(" \n", ptr + rem_width);
290 if (finalspace == std::string::npos || finalspace < ptr) {
291 // No place to break; just include the entire word and move on
292 finalspace = in.find_first_of("\n ", ptr);
293 if (finalspace == std::string::npos) {
294 // End of the string, just add it and break
295 out << in.substr(ptr);
296 break;
297 }
298 }
299 out << in.substr(ptr, finalspace - ptr) << "\n";
300 if (in[finalspace] == '\n') {
301 indented = 0;
302 } else if (indent) {
303 out << std::string(indent, ' ');
304 indented = indent;
305 }
306 ptr = finalspace + 1;
307 }
308 }
309 return out.str();
310}
311
321static const int64_t UPPER_BOUND = 1000000000000000000LL - 1LL;
322
324static inline bool ProcessMantissaDigit(char ch, int64_t &mantissa,
325 int &mantissa_tzeros) {
326 if (ch == '0') {
327 ++mantissa_tzeros;
328 } else {
329 for (int i = 0; i <= mantissa_tzeros; ++i) {
330 // overflow
331 if (mantissa > (UPPER_BOUND / 10LL)) {
332 return false;
333 }
334 mantissa *= 10;
335 }
336 mantissa += ch - '0';
337 mantissa_tzeros = 0;
338 }
339 return true;
340}
341
342bool ParseFixedPoint(std::string_view val, int decimals, int64_t *amount_out) {
343 int64_t mantissa = 0;
344 int64_t exponent = 0;
345 int mantissa_tzeros = 0;
346 bool mantissa_sign = false;
347 bool exponent_sign = false;
348 int ptr = 0;
349 int end = val.size();
350 int point_ofs = 0;
351
352 if (ptr < end && val[ptr] == '-') {
353 mantissa_sign = true;
354 ++ptr;
355 }
356 if (ptr < end) {
357 if (val[ptr] == '0') {
358 // pass single 0
359 ++ptr;
360 } else if (val[ptr] >= '1' && val[ptr] <= '9') {
361 while (ptr < end && IsDigit(val[ptr])) {
362 if (!ProcessMantissaDigit(val[ptr], mantissa,
363 mantissa_tzeros)) {
364 // overflow
365 return false;
366 }
367 ++ptr;
368 }
369 } else {
370 // missing expected digit
371 return false;
372 }
373 } else {
374 // empty string or loose '-'
375 return false;
376 }
377 if (ptr < end && val[ptr] == '.') {
378 ++ptr;
379 if (ptr < end && IsDigit(val[ptr])) {
380 while (ptr < end && IsDigit(val[ptr])) {
381 if (!ProcessMantissaDigit(val[ptr], mantissa,
382 mantissa_tzeros)) {
383 // overflow
384 return false;
385 }
386 ++ptr;
387 ++point_ofs;
388 }
389 } else {
390 // missing expected digit
391 return false;
392 }
393 }
394 if (ptr < end && (val[ptr] == 'e' || val[ptr] == 'E')) {
395 ++ptr;
396 if (ptr < end && val[ptr] == '+') {
397 ++ptr;
398 } else if (ptr < end && val[ptr] == '-') {
399 exponent_sign = true;
400 ++ptr;
401 }
402 if (ptr < end && IsDigit(val[ptr])) {
403 while (ptr < end && IsDigit(val[ptr])) {
404 if (exponent > (UPPER_BOUND / 10LL)) {
405 // overflow
406 return false;
407 }
408 exponent = exponent * 10 + val[ptr] - '0';
409 ++ptr;
410 }
411 } else {
412 // missing expected digit
413 return false;
414 }
415 }
416 if (ptr != end) {
417 // trailing garbage
418 return false;
419 }
420 // finalize exponent
421 if (exponent_sign) {
422 exponent = -exponent;
423 }
424 exponent = exponent - point_ofs + mantissa_tzeros;
425
426 // finalize mantissa
427 if (mantissa_sign) {
428 mantissa = -mantissa;
429 }
430
431 // convert to one 64-bit fixed-point value
432 exponent += decimals;
433 if (exponent < 0) {
434 // cannot represent values smaller than 10^-decimals
435 return false;
436 }
437 if (exponent >= 18) {
438 // cannot represent values larger than or equal to 10^(18-decimals)
439 return false;
440 }
441
442 for (int i = 0; i < exponent; ++i) {
443 if (mantissa > (UPPER_BOUND / 10LL) ||
444 mantissa < -(UPPER_BOUND / 10LL)) {
445 // overflow
446 return false;
447 }
448 mantissa *= 10;
449 }
450 if (mantissa > UPPER_BOUND || mantissa < -UPPER_BOUND) {
451 // overflow
452 return false;
453 }
454
455 if (amount_out) {
456 *amount_out = mantissa;
457 }
458
459 return true;
460}
461
462std::string ToLower(std::string_view str) {
463 std::string r;
464 for (auto ch : str) {
465 r += ToLower(ch);
466 }
467 return r;
468}
469
470std::string ToUpper(std::string_view str) {
471 std::string r;
472 for (auto ch : str) {
473 r += ToUpper(ch);
474 }
475 return r;
476}
477
478std::string Capitalize(std::string str) {
479 if (str.empty()) {
480 return str;
481 }
482 str[0] = ToUpper(str.front());
483 return str;
484}
constexpr std::size_t size() const noexcept
Definition: span.h:210
constexpr C * begin() const noexcept
Definition: span.h:200
constexpr C * end() const noexcept
Definition: span.h:201
signed char HexDigit(char c)
Definition: hex_base.cpp:64
constexpr auto MakeUCharSpan(V &&v) -> decltype(UCharSpanCast(Span{std::forward< V >(v)}))
Like the Span constructor, but for (const) uint8_t member types only.
Definition: span.h:350
constexpr bool IsDigit(char c)
Tests if the given character is a decimal digit.
Definition: strencodings.h:129
constexpr bool IsSpace(char c) noexcept
Tests if the given character is a whitespace character.
Definition: strencodings.h:145
std::string Capitalize(std::string str)
Capitalizes the first character of the given string.
static const std::string SAFE_CHARS[]
bool ParseInt32(std::string_view str, int32_t *out)
Convert string to signed 32-bit integer with strict parse error feedback.
std::string EncodeBase64(Span< const uint8_t > input)
bool ParseUInt16(std::string_view str, uint16_t *out)
Convert decimal string to unsigned 16-bit integer with strict parse error feedback.
std::string ToUpper(std::string_view str)
Returns the uppercase equivalent of the given string.
template std::vector< std::byte > ParseHex(std::string_view)
std::string EncodeBase32(Span< const uint8_t > input, bool pad)
Base32 encode.
bool ParseFixedPoint(std::string_view val, int decimals, int64_t *amount_out)
Parse number as fixed point according to JSON number syntax.
bool ParseInt64(std::string_view str, int64_t *out)
Convert string to signed 64-bit integer with strict parse error feedback.
bool ParseUInt8(std::string_view str, uint8_t *out)
Convert decimal string to unsigned 8-bit integer with strict parse error feedback.
bool ParseUInt64(std::string_view str, uint64_t *out)
Convert decimal string to unsigned 64-bit integer with strict parse error feedback.
static bool ProcessMantissaDigit(char ch, int64_t &mantissa, int &mantissa_tzeros)
Helper function for ParseFixedPoint.
bool IsHex(std::string_view str)
Returns true if each character in str is a hex character, and has an even number of hex digits.
std::string FormatParagraph(std::string_view in, size_t width, size_t indent)
Format a paragraph of text to a fixed width, adding spaces for indentation to any added line.
static const int64_t UPPER_BOUND
Upper bound for mantissa.
std::optional< std::vector< uint8_t > > DecodeBase64(std::string_view str)
bool SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
Splits socket address string into host string and port value.
bool ParseUInt32(std::string_view str, uint32_t *out)
Convert decimal string to unsigned 32-bit integer with strict parse error feedback.
std::optional< std::vector< Byte > > TryParseHex(std::string_view str)
Parse the hex string into bytes (uint8_t or std::byte).
std::string ToLower(std::string_view str)
Returns the lowercase equivalent of the given string.
std::optional< std::vector< uint8_t > > DecodeBase32(std::string_view str)
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
static const std::string CHARS_ALPHA_NUM