1 // Copyright (c) 2014-2015 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5 #include "base58.h"
6
7 #include "hash.h"
8 #include "uint256.h"
9
10 #include <assert.h>
11 #include <stdint.h>
12 #include <string.h>
13 #include <vector>
14 #include <string>
15 #include <boost/variant/apply_visitor.hpp>
16 #include <boost/variant/static_visitor.hpp>
17
18 /** All alphanumeric characters except for "0", "I", "O", and "l" */
19 static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
20
DecodeBase58(const char * psz,std::vector<unsigned char> & vch)21 bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
22 {
23 // Skip leading spaces.
24 while (*psz && isspace(*psz))
25 psz++;
26 // Skip and count leading '1's.
27 int zeroes = 0;
28 while (*psz == '1') {
29 zeroes++;
30 psz++;
31 }
32 // Allocate enough space in big-endian base256 representation.
33 std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up.
34 // Process the characters.
35 while (*psz && !isspace(*psz)) {
36 // Decode base58 character
37 const char* ch = strchr(pszBase58, *psz);
38 if (ch == NULL)
39 return false;
40 // Apply "b256 = b256 * 58 + ch".
41 int carry = ch - pszBase58;
42 for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {
43 carry += 58 * (*it);
44 *it = carry % 256;
45 carry /= 256;
46 }
47 assert(carry == 0);
48 psz++;
49 }
50 // Skip trailing spaces.
51 while (isspace(*psz))
52 psz++;
53 if (*psz != 0)
54 return false;
55 // Skip leading zeroes in b256.
56 std::vector<unsigned char>::iterator it = b256.begin();
57 while (it != b256.end() && *it == 0)
58 it++;
59 // Copy result into output vector.
60 vch.reserve(zeroes + (b256.end() - it));
61 vch.assign(zeroes, 0x00);
62 while (it != b256.end())
63 vch.push_back(*(it++));
64 return true;
65 }
66
EncodeBase58(const unsigned char * pbegin,const unsigned char * pend)67 std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
68 {
69 // Skip & count leading zeroes.
70 int zeroes = 0;
71 int length = 0;
72 while (pbegin != pend && *pbegin == 0) {
73 pbegin++;
74 zeroes++;
75 }
76 // Allocate enough space in big-endian base58 representation.
77 int size = (pend - pbegin) * 138 / 100 + 1; // log(256) / log(58), rounded up.
78 std::vector<unsigned char> b58(size);
79 // Process the bytes.
80 while (pbegin != pend) {
81 int carry = *pbegin;
82 int i = 0;
83 // Apply "b58 = b58 * 256 + ch".
84 for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); (carry != 0 || i < length) && (it != b58.rend()); it++, i++) {
85 carry += 256 * (*it);
86 *it = carry % 58;
87 carry /= 58;
88 }
89
90 assert(carry == 0);
91 length = i;
92 pbegin++;
93 }
94 // Skip leading zeroes in base58 result.
95 std::vector<unsigned char>::iterator it = b58.begin() + (size - length);
96 while (it != b58.end() && *it == 0)
97 it++;
98 // Translate the result into a string.
99 std::string str;
100 str.reserve(zeroes + (b58.end() - it));
101 str.assign(zeroes, '1');
102 while (it != b58.end())
103 str += pszBase58[*(it++)];
104 return str;
105 }
106
EncodeBase58(const std::vector<unsigned char> & vch)107 std::string EncodeBase58(const std::vector<unsigned char>& vch)
108 {
109 return EncodeBase58(&vch[0], &vch[0] + vch.size());
110 }
111
DecodeBase58(const std::string & str,std::vector<unsigned char> & vchRet)112 bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
113 {
114 return DecodeBase58(str.c_str(), vchRet);
115 }
116
EncodeBase58Check(const std::vector<unsigned char> & vchIn)117 std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
118 {
119 // add 4-byte hash check to the end
120 std::vector<unsigned char> vch(vchIn);
121 uint256 hash = Hash(vch.begin(), vch.end());
122 vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
123 return EncodeBase58(vch);
124 }
125
DecodeBase58Check(const char * psz,std::vector<unsigned char> & vchRet)126 bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
127 {
128 if (!DecodeBase58(psz, vchRet) ||
129 (vchRet.size() < 4)) {
130 vchRet.clear();
131 return false;
132 }
133 // re-calculate the checksum, insure it matches the included 4-byte checksum
134 uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);
135 if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {
136 vchRet.clear();
137 return false;
138 }
139 vchRet.resize(vchRet.size() - 4);
140 return true;
141 }
142
DecodeBase58Check(const std::string & str,std::vector<unsigned char> & vchRet)143 bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
144 {
145 return DecodeBase58Check(str.c_str(), vchRet);
146 }
147
CBase58Data()148 CBase58Data::CBase58Data()
149 {
150 vchVersion.clear();
151 vchData.clear();
152 }
153
SetData(const std::vector<unsigned char> & vchVersionIn,const void * pdata,size_t nSize)154 void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)
155 {
156 vchVersion = vchVersionIn;
157 vchData.resize(nSize);
158 if (!vchData.empty())
159 memcpy(&vchData[0], pdata, nSize);
160 }
161
SetData(const std::vector<unsigned char> & vchVersionIn,const unsigned char * pbegin,const unsigned char * pend)162 void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)
163 {
164 SetData(vchVersionIn, (void*)pbegin, pend - pbegin);
165 }
166
SetString(const char * psz,unsigned int nVersionBytes)167 bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)
168 {
169 std::vector<unsigned char> vchTemp;
170 bool rc58 = DecodeBase58Check(psz, vchTemp);
171 if ((!rc58) || (vchTemp.size() < nVersionBytes)) {
172 vchData.clear();
173 vchVersion.clear();
174 return false;
175 }
176 vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);
177 vchData.resize(vchTemp.size() - nVersionBytes);
178 if (!vchData.empty())
179 memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size());
180 memory_cleanse(&vchTemp[0], vchTemp.size());
181 return true;
182 }
183
SetString(const std::string & str)184 bool CBase58Data::SetString(const std::string& str)
185 {
186 return SetString(str.c_str());
187 }
188
ToString() const189 std::string CBase58Data::ToString() const
190 {
191 std::vector<unsigned char> vch = vchVersion;
192 vch.insert(vch.end(), vchData.begin(), vchData.end());
193 return EncodeBase58Check(vch);
194 }
195
CompareTo(const CBase58Data & b58) const196 int CBase58Data::CompareTo(const CBase58Data& b58) const
197 {
198 if (vchVersion < b58.vchVersion)
199 return -1;
200 if (vchVersion > b58.vchVersion)
201 return 1;
202 if (vchData < b58.vchData)
203 return -1;
204 if (vchData > b58.vchData)
205 return 1;
206 return 0;
207 }
208
209 namespace
210 {
211 class CBitcoinAddressVisitor : public boost::static_visitor<bool>
212 {
213 private:
214 CBitcoinAddress* addr;
215
216 public:
CBitcoinAddressVisitor(CBitcoinAddress * addrIn)217 CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {}
218
operator ()(const CKeyID & id) const219 bool operator()(const CKeyID& id) const { return addr->Set(id); }
operator ()(const CScriptID & id) const220 bool operator()(const CScriptID& id) const { return addr->Set(id); }
operator ()(const CNoDestination & no) const221 bool operator()(const CNoDestination& no) const { return false; }
222 };
223
224 } // anon namespace
225
Set(const CKeyID & id)226 bool CBitcoinAddress::Set(const CKeyID& id)
227 {
228 SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);
229 return true;
230 }
231
Set(const CScriptID & id)232 bool CBitcoinAddress::Set(const CScriptID& id)
233 {
234 SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);
235 return true;
236 }
237
Set(const CTxDestination & dest)238 bool CBitcoinAddress::Set(const CTxDestination& dest)
239 {
240 return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
241 }
242
IsValid() const243 bool CBitcoinAddress::IsValid() const
244 {
245 return IsValid(Params());
246 }
247
IsValid(const CChainParams & params) const248 bool CBitcoinAddress::IsValid(const CChainParams& params) const
249 {
250 bool fCorrectSize = vchData.size() == 20;
251 bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
252 vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
253 return fCorrectSize && fKnownVersion;
254 }
255
Get() const256 CTxDestination CBitcoinAddress::Get() const
257 {
258 if (!IsValid())
259 return CNoDestination();
260 uint160 id;
261 memcpy(&id, &vchData[0], 20);
262 if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
263 return CKeyID(id);
264 else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))
265 return CScriptID(id);
266 else
267 return CNoDestination();
268 }
269
GetKeyID(CKeyID & keyID) const270 bool CBitcoinAddress::GetKeyID(CKeyID& keyID) const
271 {
272 if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
273 return false;
274 uint160 id;
275 memcpy(&id, &vchData[0], 20);
276 keyID = CKeyID(id);
277 return true;
278 }
279
IsScript() const280 bool CBitcoinAddress::IsScript() const
281 {
282 return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
283 }
284
SetKey(const CKey & vchSecret)285 void CBitcoinSecret::SetKey(const CKey& vchSecret)
286 {
287 assert(vchSecret.IsValid());
288 SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
289 if (vchSecret.IsCompressed())
290 vchData.push_back(1);
291 }
292
GetKey()293 CKey CBitcoinSecret::GetKey()
294 {
295 CKey ret;
296 assert(vchData.size() >= 32);
297 ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);
298 return ret;
299 }
300
IsValid() const301 bool CBitcoinSecret::IsValid() const
302 {
303 bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);
304 bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY);
305 return fExpectedFormat && fCorrectVersion;
306 }
307
SetString(const char * pszSecret)308 bool CBitcoinSecret::SetString(const char* pszSecret)
309 {
310 return CBase58Data::SetString(pszSecret) && IsValid();
311 }
312
SetString(const std::string & strSecret)313 bool CBitcoinSecret::SetString(const std::string& strSecret)
314 {
315 return SetString(strSecret.c_str());
316 }
317