Use standard C99 (and Qt) types for 64-bit integers
[novacoin.git] / src / base58.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin Developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt 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 // - Doubleclicking selects the whole number as one word if it's all alphanumeric.
14 //
15 #ifndef BITCOIN_BASE58_H
16 #define BITCOIN_BASE58_H
17
18 #include <stdint.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 0 (or 192 testnet)
259 // The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key
260 // Script-hash-addresses (OP_EVAL) have version 5 (or 196 testnet)
261 // The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script
262 class CBitcoinAddress : public CBase58Data
263 {
264 public:
265     enum
266     {
267         PUBKEY_ADDRESS = 0,
268         SCRIPT_ADDRESS = 5,
269         PUBKEY_ADDRESS_TEST = 192,
270         PUBKEY_ADDRESS_TEST_LEGACY = 111,  // Deprecated: old testnet address
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         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; // OP_EVAL, hash of CScript
303                 fExpectTestNet = false;
304                 break;
305
306             case PUBKEY_ADDRESS_TEST_LEGACY:
307             case PUBKEY_ADDRESS_TEST:
308                 nExpectedSize = 20;
309                 fExpectTestNet = true;
310                 break;
311             case SCRIPT_ADDRESS_TEST:
312                 nExpectedSize = 20;
313                 fExpectTestNet = true;
314                 break;
315
316             default:
317                 return false;
318         }
319         return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize;
320     }
321     bool IsScript() const
322     {
323         if (!IsValid())
324             return false;
325         if (fTestNet)
326             return nVersion == SCRIPT_ADDRESS_TEST;
327         return nVersion == SCRIPT_ADDRESS;
328     }
329
330     CBitcoinAddress()
331     {
332     }
333
334     CBitcoinAddress(uint160 hash160In)
335     {
336         SetHash160(hash160In);
337     }
338
339     CBitcoinAddress(const std::vector<unsigned char>& vchPubKey)
340     {
341         SetPubKey(vchPubKey);
342     }
343
344     CBitcoinAddress(const std::string& strAddress)
345     {
346         SetString(strAddress);
347     }
348
349     CBitcoinAddress(const char* pszAddress)
350     {
351         SetString(pszAddress);
352     }
353
354     uint160 GetHash160() const
355     {
356         assert(vchData.size() == 20);
357         uint160 hash160;
358         memcpy(&hash160, &vchData[0], 20);
359         return hash160;
360     }
361 };
362
363 class CBitcoinSecret : public CBase58Data
364 {
365 public:
366     void SetSecret(const CSecret& vchSecret)
367     {
368         SetData(fTestNet ? 239 : 128, &vchSecret[0], vchSecret.size());
369     }
370
371     CSecret GetSecret()
372     {
373         CSecret vchSecret;
374         vchSecret.resize(vchData.size());
375         memcpy(&vchSecret[0], &vchData[0], vchData.size());
376         return vchSecret;
377     }
378
379     bool IsValid() const
380     {
381         int nExpectedSize = 32;
382         bool fExpectTestNet = false;
383         switch(nVersion)
384         {
385             case 128:
386                 break;
387
388             case 239:
389                 fExpectTestNet = true;
390                 break;
391
392             default:
393                 return false;
394         }
395         return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize;
396     }
397
398     CBitcoinSecret(const CSecret& vchSecret)
399     {
400         SetSecret(vchSecret);
401     }
402
403     CBitcoinSecret()
404     {
405     }
406 };
407
408 #endif