Merge with Bitcoin v0.6.3
[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 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6
7
8 //
9 // Why base-58 instead of standard base-64 encoding?
10 // - Don't want 0OIl characters that look the same in some fonts and
11 //      could be used to create visually identical looking account numbers.
12 // - A string with non-alphanumeric characters is not as easily accepted as an account number.
13 // - E-mail usually won't line-break if there's no punctuation to break at.
14 // - Doubleclicking selects the whole number as one word if it's all alphanumeric.
15 //
16 #ifndef BITCOIN_BASE58_H
17 #define BITCOIN_BASE58_H
18
19 #include <string>
20 #include <vector>
21 #include "bignum.h"
22 #include "key.h"
23
24 static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
25
26 // Encode a byte sequence as a base58-encoded string
27 inline 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.getulong();
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 inline 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 succesful
75 inline 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.setulong(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 succesful
123 inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
124 {
125     return DecodeBase58(str.c_str(), vchRet);
126 }
127
128
129
130
131 // Encode a byte vector to a base58-encoded string, including checksum
132 inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
133 {
134     // add 4-byte hash check to the end
135     std::vector<unsigned char> vch(vchIn);
136     uint256 hash = Hash(vch.begin(), vch.end());
137     vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
138     return EncodeBase58(vch);
139 }
140
141 // Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet
142 // returns true if decoding is succesful
143 inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
144 {
145     if (!DecodeBase58(psz, vchRet))
146         return false;
147     if (vchRet.size() < 4)
148     {
149         vchRet.clear();
150         return false;
151     }
152     uint256 hash = Hash(vchRet.begin(), vchRet.end()-4);
153     if (memcmp(&hash, &vchRet.end()[-4], 4) != 0)
154     {
155         vchRet.clear();
156         return false;
157     }
158     vchRet.resize(vchRet.size()-4);
159     return true;
160 }
161
162 // Decode a base58-encoded string str that includes a checksum, into byte vector vchRet
163 // returns true if decoding is succesful
164 inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
165 {
166     return DecodeBase58Check(str.c_str(), vchRet);
167 }
168
169
170
171
172
173 /** Base class for all base58-encoded data */
174 class CBase58Data
175 {
176 protected:
177     // the version byte
178     unsigned char nVersion;
179
180     // the actually encoded data
181     std::vector<unsigned char> vchData;
182
183     CBase58Data()
184     {
185         nVersion = 0;
186         vchData.clear();
187     }
188
189     ~CBase58Data()
190     {
191         // zero the memory, as it may contain sensitive data
192         if (!vchData.empty())
193             memset(&vchData[0], 0, vchData.size());
194     }
195
196     void SetData(int nVersionIn, const void* pdata, size_t nSize)
197     {
198         nVersion = nVersionIn;
199         vchData.resize(nSize);
200         if (!vchData.empty())
201             memcpy(&vchData[0], pdata, nSize);
202     }
203
204     void SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend)
205     {
206         SetData(nVersionIn, (void*)pbegin, pend - pbegin);
207     }
208
209 public:
210     bool SetString(const char* psz)
211     {
212         std::vector<unsigned char> vchTemp;
213         DecodeBase58Check(psz, vchTemp);
214         if (vchTemp.empty())
215         {
216             vchData.clear();
217             nVersion = 0;
218             return false;
219         }
220         nVersion = vchTemp[0];
221         vchData.resize(vchTemp.size() - 1);
222         if (!vchData.empty())
223             memcpy(&vchData[0], &vchTemp[1], vchData.size());
224         memset(&vchTemp[0], 0, vchTemp.size());
225         return true;
226     }
227
228     bool SetString(const std::string& str)
229     {
230         return SetString(str.c_str());
231     }
232
233     std::string ToString() const
234     {
235         std::vector<unsigned char> vch(1, nVersion);
236         vch.insert(vch.end(), vchData.begin(), vchData.end());
237         return EncodeBase58Check(vch);
238     }
239
240     int CompareTo(const CBase58Data& b58) const
241     {
242         if (nVersion < b58.nVersion) return -1;
243         if (nVersion > b58.nVersion) return  1;
244         if (vchData < b58.vchData)   return -1;
245         if (vchData > b58.vchData)   return  1;
246         return 0;
247     }
248
249     bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; }
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 };
255
256 /** base58-encoded bitcoin addresses.
257  * Public-key-hash-addresses have version 55 (or 111 testnet).
258  * The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
259  * Script-hash-addresses have version 57 (or 196 testnet).
260  * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
261  */
262 class CBitcoinAddress : public CBase58Data
263 {
264 public:
265     enum
266     {
267         PUBKEY_ADDRESS = 55,  // ppcoin: addresses begin with 'P'
268         SCRIPT_ADDRESS = 57,  // ppcoin: addresses begin with 'Q'
269         PUBKEY_ADDRESS_TEST = 111,
270         SCRIPT_ADDRESS_TEST = 196,
271     };
272
273     bool SetHash160(const uint160& hash160)
274     {
275         SetData(fTestNet ? PUBKEY_ADDRESS_TEST : PUBKEY_ADDRESS, &hash160, 20);
276         return true;
277     }
278
279     void SetPubKey(const std::vector<unsigned char>& vchPubKey)
280     {
281         SetHash160(Hash160(vchPubKey));
282     }
283
284     bool SetScriptHash160(const uint160& hash160)
285     {
286         SetData(fTestNet ? SCRIPT_ADDRESS_TEST : SCRIPT_ADDRESS, &hash160, 20);
287         return true;
288     }
289
290     bool IsValid() const
291     {
292         unsigned int nExpectedSize = 20;
293         bool fExpectTestNet = false;
294         switch(nVersion)
295         {
296             case PUBKEY_ADDRESS:
297                 nExpectedSize = 20; // Hash of public key
298                 fExpectTestNet = false;
299                 break;
300             case SCRIPT_ADDRESS:
301                 nExpectedSize = 20; // Hash of CScript
302                 fExpectTestNet = false;
303                 break;
304
305             case PUBKEY_ADDRESS_TEST:
306                 nExpectedSize = 20;
307                 fExpectTestNet = true;
308                 break;
309             case SCRIPT_ADDRESS_TEST:
310                 nExpectedSize = 20;
311                 fExpectTestNet = true;
312                 break;
313
314             default:
315                 return false;
316         }
317         return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize;
318     }
319     bool IsScript() const
320     {
321         if (!IsValid())
322             return false;
323         if (fTestNet)
324             return nVersion == SCRIPT_ADDRESS_TEST;
325         return nVersion == SCRIPT_ADDRESS;
326     }
327
328     CBitcoinAddress()
329     {
330     }
331
332     CBitcoinAddress(uint160 hash160In)
333     {
334         SetHash160(hash160In);
335     }
336
337     CBitcoinAddress(const std::vector<unsigned char>& vchPubKey)
338     {
339         SetPubKey(vchPubKey);
340     }
341
342     CBitcoinAddress(const std::string& strAddress)
343     {
344         SetString(strAddress);
345     }
346
347     CBitcoinAddress(const char* pszAddress)
348     {
349         SetString(pszAddress);
350     }
351
352     uint160 GetHash160() const
353     {
354         assert(vchData.size() == 20);
355         uint160 hash160;
356         memcpy(&hash160, &vchData[0], 20);
357         return hash160;
358     }
359 };
360
361 /** A base58-encoded secret key */
362 class CBitcoinSecret : public CBase58Data
363 {
364 public:
365     void SetSecret(const CSecret& vchSecret, bool fCompressed)
366     { 
367         assert(vchSecret.size() == 32);
368         SetData(fTestNet ? 239 : 128, &vchSecret[0], vchSecret.size());
369         if (fCompressed)
370             vchData.push_back(1);
371     }
372
373     CSecret GetSecret(bool &fCompressedOut)
374     {
375         CSecret vchSecret;
376         vchSecret.resize(32);
377         memcpy(&vchSecret[0], &vchData[0], 32);
378         fCompressedOut = vchData.size() == 33;
379         return vchSecret;
380     }
381
382     bool IsValid() const
383     {
384         bool fExpectTestNet = false;
385         switch(nVersion)
386         {
387             case 128:
388                 break;
389
390             case 239:
391                 fExpectTestNet = true;
392                 break;
393
394             default:
395                 return false;
396         }
397         return fExpectTestNet == fTestNet && (vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1));
398     }
399
400     bool SetString(const char* pszSecret)
401     {
402         return CBase58Data::SetString(pszSecret) && IsValid();
403     }
404
405     bool SetString(const std::string& strSecret)
406     {
407         return SetString(strSecret.c_str());
408     }
409
410     CBitcoinSecret(const CSecret& vchSecret, bool fCompressed)
411     {
412         SetSecret(vchSecret, fCompressed);
413     }
414
415     CBitcoinSecret()
416     {
417     }
418 };
419
420 #endif