1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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 /**
7  * Utilities for converting data from/to strings.
8  */
9 #ifndef BITCOIN_UTILSTRENCODINGS_H
10 #define BITCOIN_UTILSTRENCODINGS_H
11 
12 #include <stdint.h>
13 #include <string>
14 #include <vector>
15 
16 #define BEGIN(a)            ((char*)&(a))
17 #define END(a)              ((char*)&((&(a))[1]))
18 #define UBEGIN(a)           ((unsigned char*)&(a))
19 #define UEND(a)             ((unsigned char*)&((&(a))[1]))
20 #define ARRAYLEN(array)     (sizeof(array)/sizeof((array)[0]))
21 
22 /** This is needed because the foreach macro can't get over the comma in pair<t1, t2> */
23 #define PAIRTYPE(t1, t2)    std::pair<t1, t2>
24 
25 /** Used by SanitizeString() */
26 enum SafeChars
27 {
28     SAFE_CHARS_DEFAULT, //!< The full set of allowed chars
29     SAFE_CHARS_UA_COMMENT //!< BIP-0014 subset
30 };
31 
32 /**
33 * Remove unsafe chars. Safe chars chosen to allow simple messages/URLs/email
34 * addresses, but avoid anything even possibly remotely dangerous like & or >
35 * @param[in] str    The string to sanitize
36 * @param[in] rule   The set of safe chars to choose (default: least restrictive)
37 * @return           A new string without unsafe chars
38 */
39 std::string SanitizeString(const std::string& str, int rule = SAFE_CHARS_DEFAULT);
40 std::vector<unsigned char> ParseHex(const char* psz);
41 std::vector<unsigned char> ParseHex(const std::string& str);
42 signed char HexDigit(char c);
43 bool IsHex(const std::string& str);
44 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
45 std::string DecodeBase64(const std::string& str);
46 std::string EncodeBase64(const unsigned char* pch, size_t len);
47 std::string EncodeBase64(const std::string& str);
48 std::vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid = NULL);
49 std::string DecodeBase32(const std::string& str);
50 std::string EncodeBase32(const unsigned char* pch, size_t len);
51 std::string EncodeBase32(const std::string& str);
52 
53 std::string i64tostr(int64_t n);
54 std::string itostr(int n);
55 int64_t atoi64(const char* psz);
56 int64_t atoi64(const std::string& str);
57 int atoi(const std::string& str);
58 
59 /**
60  * Convert string to signed 32-bit integer with strict parse error feedback.
61  * @returns true if the entire string could be parsed as valid integer,
62  *   false if not the entire string could be parsed or when overflow or underflow occurred.
63  */
64 bool ParseInt32(const std::string& str, int32_t *out);
65 
66 /**
67  * Convert string to signed 64-bit integer with strict parse error feedback.
68  * @returns true if the entire string could be parsed as valid integer,
69  *   false if not the entire string could be parsed or when overflow or underflow occurred.
70  */
71 bool ParseInt64(const std::string& str, int64_t *out);
72 
73 /**
74  * Convert decimal string to unsigned 32-bit integer with strict parse error feedback.
75  * @returns true if the entire string could be parsed as valid integer,
76  *   false if not the entire string could be parsed or when overflow or underflow occurred.
77  */
78 bool ParseUInt32(const std::string& str, uint32_t *out);
79 
80 /**
81  * Convert decimal string to unsigned 64-bit integer with strict parse error feedback.
82  * @returns true if the entire string could be parsed as valid integer,
83  *   false if not the entire string could be parsed or when overflow or underflow occurred.
84  */
85 bool ParseUInt64(const std::string& str, uint64_t *out);
86 
87 /**
88  * Convert string to double with strict parse error feedback.
89  * @returns true if the entire string could be parsed as valid double,
90  *   false if not the entire string could be parsed or when overflow or underflow occurred.
91  */
92 bool ParseDouble(const std::string& str, double *out);
93 
94 template<typename T>
95 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
96 {
97     std::string rv;
98     static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
99                                      '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
100     rv.reserve((itend-itbegin)*3);
101     for(T it = itbegin; it < itend; ++it)
102     {
103         unsigned char val = (unsigned char)(*it);
104         if(fSpaces && it != itbegin)
105             rv.push_back(' ');
106         rv.push_back(hexmap[val>>4]);
107         rv.push_back(hexmap[val&15]);
108     }
109 
110     return rv;
111 }
112 
113 template<typename T>
114 inline std::string HexStr(const T& vch, bool fSpaces=false)
115 {
116     return HexStr(vch.begin(), vch.end(), fSpaces);
117 }
118 
119 /**
120  * Format a paragraph of text to a fixed width, adding spaces for
121  * indentation to any added line.
122  */
123 std::string FormatParagraph(const std::string& in, size_t width = 79, size_t indent = 0);
124 
125 /**
126  * Timing-attack-resistant comparison.
127  * Takes time proportional to length
128  * of first argument.
129  */
130 template <typename T>
TimingResistantEqual(const T & a,const T & b)131 bool TimingResistantEqual(const T& a, const T& b)
132 {
133     if (b.size() == 0) return a.size() == 0;
134     size_t accumulator = a.size() ^ b.size();
135     for (size_t i = 0; i < a.size(); i++)
136         accumulator |= a[i] ^ b[i%b.size()];
137     return accumulator == 0;
138 }
139 
140 /** Parse number as fixed point according to JSON number syntax.
141  * See http://json.org/number.gif
142  * @returns true on success, false on error.
143  * @note The result must be in the range (-10^18,10^18), otherwise an overflow error will trigger.
144  */
145 bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out);
146 
147 #endif // BITCOIN_UTILSTRENCODINGS_H
148