FormatMoney cleanup
[novacoin.git] / src / base58.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin Developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6
7 //
8 // Why base-58 instead of standard base-64 encoding?
9 // - Don't want 0OIl characters that look the same in some fonts and
10 //      could be used to create visually identical looking account numbers.
11 // - A string with non-alphanumeric characters is not as easily accepted as an account number.
12 // - E-mail usually won't line-break if there's no punctuation to break at.
13 // - Double-clicking selects the whole number as one word if it's all alphanumeric.
14 //
15
16 #include <string>
17 #include <vector>
18 #include <openssl/crypto.h> // for OPENSSL_cleanse()
19 #include "bignum.h"
20 #include "key.h"
21 #include "script.h"
22 #include "base58.h"
23
24 static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
25
26 // Encode a byte sequence as a base58-encoded string
27 std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
28 {
29     CAutoBN_CTX pctx;
30     CBigNum bn58 = 58;
31     CBigNum bn0 = 0;
32
33     // Convert big endian data to little endian
34     // Extra zero at the end make sure bignum will interpret as a positive number
35     std::vector<unsigned char> vchTmp(pend-pbegin+1, 0);
36     reverse_copy(pbegin, pend, vchTmp.begin());
37
38     // Convert little endian data to bignum
39     CBigNum bn;
40     bn.setvch(vchTmp);
41
42     // Convert bignum to std::string
43     std::string str;
44     // Expected size increase from base58 conversion is approximately 137%
45     // use 138% to be safe
46     str.reserve((pend - pbegin) * 138 / 100 + 1);
47     CBigNum dv;
48     CBigNum rem;
49     while (bn > bn0)
50     {
51         if (!BN_div(&dv, &rem, &bn, &bn58, pctx))
52             throw bignum_error("EncodeBase58 : BN_div failed");
53         bn = dv;
54         unsigned int c = rem.getuint32();
55         str += pszBase58[c];
56     }
57
58     // Leading zeroes encoded as base58 zeros
59     for (const unsigned char* p = pbegin; p < pend && *p == 0; p++)
60         str += pszBase58[0];
61
62     // Convert little endian std::string to big endian
63     reverse(str.begin(), str.end());
64     return str;
65 }
66
67 // Encode a byte vector as a base58-encoded string
68 std::string EncodeBase58(const std::vector<unsigned char>& vch)
69 {
70     return EncodeBase58(&vch[0], &vch[0] + vch.size());
71 }
72
73 // Decode a base58-encoded string psz into byte vector vchRet
74 // returns true if decoding is successful
75 bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet)
76 {
77     CAutoBN_CTX pctx;
78     vchRet.clear();
79     CBigNum bn58 = 58;
80     CBigNum bn = 0;
81     CBigNum bnChar;
82     while (isspace(*psz))
83         psz++;
84
85     // Convert big endian string to bignum
86     for (const char* p = psz; *p; p++)
87     {
88         const char* p1 = strchr(pszBase58, *p);
89         if (p1 == NULL)
90         {
91             while (isspace(*p))
92                 p++;
93             if (*p != '\0')
94                 return false;
95             break;
96         }
97         bnChar.setuint32((uint32_t)(p1 - pszBase58));
98         if (!BN_mul(&bn, &bn, &bn58, pctx))
99             throw bignum_error("DecodeBase58 : BN_mul failed");
100         bn += bnChar;
101     }
102
103     // Get bignum as little endian data
104     std::vector<unsigned char> vchTmp = bn.getvch();
105
106     // Trim off sign byte if present
107     if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80)
108         vchTmp.erase(vchTmp.end()-1);
109
110     // Restore leading zeros
111     int nLeadingZeros = 0;
112     for (const char* p = psz; *p == pszBase58[0]; p++)
113         nLeadingZeros++;
114     vchRet.assign(nLeadingZeros + vchTmp.size(), 0);
115
116     // Convert little endian data to big endian
117     reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size());
118     return true;
119 }
120
121 // Decode a base58-encoded string str into byte vector vchRet
122 // returns true if decoding is successful
123 bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
124 {
125     return DecodeBase58(str.c_str(), vchRet);
126 }
127
128 // Encode a byte vector to a base58-encoded string, including checksum
129 std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
130 {
131     // add 4-byte hash check to the end
132     std::vector<unsigned char> vch(vchIn);
133     uint256 hash = Hash(vch.begin(), vch.end());
134     vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
135     return EncodeBase58(vch);
136 }
137
138 // Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet
139 // returns true if decoding is successful
140 bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
141 {
142     if (!DecodeBase58(psz, vchRet))
143         return false;
144     if (vchRet.size() < 4)
145     {
146         vchRet.clear();
147         return false;
148     }
149     uint256 hash = Hash(vchRet.begin(), vchRet.end()-4);
150     if (memcmp(&hash, &vchRet.end()[-4], 4) != 0)
151     {
152         vchRet.clear();
153         return false;
154     }
155     vchRet.resize(vchRet.size()-4);
156     return true;
157 }
158
159 // Decode a base58-encoded string str that includes a checksum, into byte vector vchRet
160 // returns true if decoding is successful
161 bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
162 {
163     return DecodeBase58Check(str.c_str(), vchRet);
164 }
165
166     CBase58Data::CBase58Data()
167     {
168         nVersion = 0;
169         vchData.clear();
170     }
171
172     CBase58Data::~CBase58Data()
173     {
174         // zero the memory, as it may contain sensitive data
175         if (!vchData.empty())
176             OPENSSL_cleanse(&vchData[0], vchData.size());
177     }
178
179     void CBase58Data::SetData(int nVersionIn, const void* pdata, size_t nSize)
180     {
181         nVersion = nVersionIn;
182         vchData.resize(nSize);
183         if (!vchData.empty())
184             memcpy(&vchData[0], pdata, nSize);
185     }
186
187     void CBase58Data::SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend)
188     {
189         SetData(nVersionIn, (void*)pbegin, pend - pbegin);
190     }
191
192     bool CBase58Data::SetString(const char* psz)
193     {
194         std::vector<unsigned char> vchTemp;
195         DecodeBase58Check(psz, vchTemp);
196         if (vchTemp.empty())
197         {
198             vchData.clear();
199             nVersion = 0;
200             return false;
201         }
202         nVersion = vchTemp[0];
203         vchData.resize(vchTemp.size() - 1);
204         if (!vchData.empty())
205             memcpy(&vchData[0], &vchTemp[1], vchData.size());
206         OPENSSL_cleanse(&vchTemp[0], vchData.size());
207         return true;
208     }
209
210     bool CBase58Data::SetString(const std::string& str)
211     {
212         return SetString(str.c_str());
213     }
214
215     std::string CBase58Data::ToString() const
216     {
217         std::vector<unsigned char> vch(1, nVersion);
218         vch.insert(vch.end(), vchData.begin(), vchData.end());
219         return EncodeBase58Check(vch);
220     }
221
222     int CBase58Data::CompareTo(const CBase58Data& b58) const
223     {
224         if (nVersion < b58.nVersion) return -1;
225         if (nVersion > b58.nVersion) return  1;
226         if (vchData < b58.vchData)   return -1;
227         if (vchData > b58.vchData)   return  1;
228         return 0;
229     }
230
231     bool CBitcoinAddress::Set(const CKeyID &id) {
232         SetData(fTestNet ? PUBKEY_ADDRESS_TEST : PUBKEY_ADDRESS, &id, 20);
233         return true;
234     }
235
236     bool CBitcoinAddress::Set(const CScriptID &id) {
237         SetData(fTestNet ? SCRIPT_ADDRESS_TEST : SCRIPT_ADDRESS, &id, 20);
238         return true;
239     }
240
241     bool CBitcoinAddress::Set(const CTxDestination &dest)
242     {
243         return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
244     }
245
246     bool CBitcoinAddress::IsValid() const
247     {
248         unsigned int nExpectedSize = 20;
249         bool fExpectTestNet = false;
250         switch(nVersion)
251         {
252             case PUBKEY_ADDRESS:
253                 nExpectedSize = 20; // Hash of public key
254                 fExpectTestNet = false;
255                 break;
256             case SCRIPT_ADDRESS:
257                 nExpectedSize = 20; // Hash of CScript
258                 fExpectTestNet = false;
259                 break;
260
261             case PUBKEY_ADDRESS_TEST:
262                 nExpectedSize = 20;
263                 fExpectTestNet = true;
264                 break;
265             case SCRIPT_ADDRESS_TEST:
266                 nExpectedSize = 20;
267                 fExpectTestNet = true;
268                 break;
269
270             default:
271                 return false;
272         }
273         return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize;
274     }
275
276     CTxDestination CBitcoinAddress::Get() const {
277         if (!IsValid())
278             return CNoDestination();
279         switch (nVersion) {
280         case PUBKEY_ADDRESS:
281         case PUBKEY_ADDRESS_TEST: {
282             uint160 id;
283             memcpy(&id, &vchData[0], 20);
284             return CKeyID(id);
285         }
286         case SCRIPT_ADDRESS:
287         case SCRIPT_ADDRESS_TEST: {
288             uint160 id;
289             memcpy(&id, &vchData[0], 20);
290             return CScriptID(id);
291         }
292         }
293         return CNoDestination();
294     }
295
296     bool CBitcoinAddress::GetKeyID(CKeyID &keyID) const {
297         if (!IsValid())
298             return false;
299         switch (nVersion) {
300         case PUBKEY_ADDRESS:
301         case PUBKEY_ADDRESS_TEST: {
302             uint160 id;
303             memcpy(&id, &vchData[0], 20);
304             keyID = CKeyID(id);
305             return true;
306         }
307         default: return false;
308         }
309     }
310
311     bool CBitcoinAddress::IsScript() const {
312         if (!IsValid())
313             return false;
314         switch (nVersion) {
315         case SCRIPT_ADDRESS:
316         case SCRIPT_ADDRESS_TEST: {
317             return true;
318         }
319         default: return false;
320         }
321     }
322
323     void CBitcoinSecret::SetSecret(const CSecret& vchSecret, bool fCompressed)
324     {
325         assert(vchSecret.size() == 32);
326         SetData(128 + (fTestNet ? CBitcoinAddress::PUBKEY_ADDRESS_TEST : CBitcoinAddress::PUBKEY_ADDRESS), &vchSecret[0], vchSecret.size());
327         if (fCompressed)
328             vchData.push_back(1);
329     }
330
331     CSecret CBitcoinSecret::GetSecret(bool &fCompressedOut)
332     {
333         CSecret vchSecret;
334         vchSecret.resize(32);
335         memcpy(&vchSecret[0], &vchData[0], 32);
336         fCompressedOut = vchData.size() == 33;
337         return vchSecret;
338     }
339
340     bool CBitcoinSecret::IsValid() const
341     {
342         bool fExpectTestNet = false;
343         switch(nVersion)
344         {
345             case (128 + CBitcoinAddress::PUBKEY_ADDRESS):
346                 break;
347
348             case (128 + CBitcoinAddress::PUBKEY_ADDRESS_TEST):
349                 fExpectTestNet = true;
350                 break;
351
352             default:
353                 return false;
354         }
355         return fExpectTestNet == fTestNet && (vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1));
356     }
357
358     bool CBitcoinSecret::SetString(const char* pszSecret)
359     {
360         return CBase58Data::SetString(pszSecret) && IsValid();
361     }
362
363     bool CBitcoinSecret::SetString(const std::string& strSecret)
364     {
365         return SetString(strSecret.c_str());
366     }
367
368     CBitcoinSecret::CBitcoinSecret(const CSecret& vchSecret, bool fCompressed)
369     {
370         SetSecret(vchSecret, fCompressed);
371     }
372
373