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