Update License in File Headers
[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 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 // - 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 <string>
19 #include <vector>
20 #include "bignum.h"
21
22 static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
23
24
25 inline std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
26 {
27     CAutoBN_CTX pctx;
28     CBigNum bn58 = 58;
29     CBigNum bn0 = 0;
30
31     // Convert big endian data to little endian
32     // Extra zero at the end make sure bignum will interpret as a positive number
33     std::vector<unsigned char> vchTmp(pend-pbegin+1, 0);
34     reverse_copy(pbegin, pend, vchTmp.begin());
35
36     // Convert little endian data to bignum
37     CBigNum bn;
38     bn.setvch(vchTmp);
39
40     // Convert bignum to std::string
41     std::string str;
42     // Expected size increase from base58 conversion is approximately 137%
43     // use 138% to be safe
44     str.reserve((pend - pbegin) * 138 / 100 + 1);
45     CBigNum dv;
46     CBigNum rem;
47     while (bn > bn0)
48     {
49         if (!BN_div(&dv, &rem, &bn, &bn58, pctx))
50             throw bignum_error("EncodeBase58 : BN_div failed");
51         bn = dv;
52         unsigned int c = rem.getulong();
53         str += pszBase58[c];
54     }
55
56     // Leading zeroes encoded as base58 zeros
57     for (const unsigned char* p = pbegin; p < pend && *p == 0; p++)
58         str += pszBase58[0];
59
60     // Convert little endian std::string to big endian
61     reverse(str.begin(), str.end());
62     return str;
63 }
64
65 inline std::string EncodeBase58(const std::vector<unsigned char>& vch)
66 {
67     return EncodeBase58(&vch[0], &vch[0] + vch.size());
68 }
69
70 inline bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet)
71 {
72     CAutoBN_CTX pctx;
73     vchRet.clear();
74     CBigNum bn58 = 58;
75     CBigNum bn = 0;
76     CBigNum bnChar;
77     while (isspace(*psz))
78         psz++;
79
80     // Convert big endian string to bignum
81     for (const char* p = psz; *p; p++)
82     {
83         const char* p1 = strchr(pszBase58, *p);
84         if (p1 == NULL)
85         {
86             while (isspace(*p))
87                 p++;
88             if (*p != '\0')
89                 return false;
90             break;
91         }
92         bnChar.setulong(p1 - pszBase58);
93         if (!BN_mul(&bn, &bn, &bn58, pctx))
94             throw bignum_error("DecodeBase58 : BN_mul failed");
95         bn += bnChar;
96     }
97
98     // Get bignum as little endian data
99     std::vector<unsigned char> vchTmp = bn.getvch();
100
101     // Trim off sign byte if present
102     if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80)
103         vchTmp.erase(vchTmp.end()-1);
104
105     // Restore leading zeros
106     int nLeadingZeros = 0;
107     for (const char* p = psz; *p == pszBase58[0]; p++)
108         nLeadingZeros++;
109     vchRet.assign(nLeadingZeros + vchTmp.size(), 0);
110
111     // Convert little endian data to big endian
112     reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size());
113     return true;
114 }
115
116 inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
117 {
118     return DecodeBase58(str.c_str(), vchRet);
119 }
120
121
122
123
124
125 inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
126 {
127     // add 4-byte hash check to the end
128     std::vector<unsigned char> vch(vchIn);
129     uint256 hash = Hash(vch.begin(), vch.end());
130     vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
131     return EncodeBase58(vch);
132 }
133
134 inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
135 {
136     if (!DecodeBase58(psz, vchRet))
137         return false;
138     if (vchRet.size() < 4)
139     {
140         vchRet.clear();
141         return false;
142     }
143     uint256 hash = Hash(vchRet.begin(), vchRet.end()-4);
144     if (memcmp(&hash, &vchRet.end()[-4], 4) != 0)
145     {
146         vchRet.clear();
147         return false;
148     }
149     vchRet.resize(vchRet.size()-4);
150     return true;
151 }
152
153 inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
154 {
155     return DecodeBase58Check(str.c_str(), vchRet);
156 }
157
158
159
160
161
162
163 class CBase58Data
164 {
165 protected:
166     unsigned char nVersion;
167     std::vector<unsigned char> vchData;
168
169     CBase58Data()
170     {
171         nVersion = 0;
172         vchData.clear();
173     }
174
175     ~CBase58Data()
176     {
177         if (!vchData.empty())
178             memset(&vchData[0], 0, vchData.size());
179     }
180
181     void SetData(int nVersionIn, const void* pdata, size_t nSize)
182     {
183         nVersion = nVersionIn;
184         vchData.resize(nSize);
185         if (!vchData.empty())
186             memcpy(&vchData[0], pdata, nSize);
187     }
188
189     void SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend)
190     {
191         SetData(nVersionIn, (void*)pbegin, pend - pbegin);
192     }
193
194 public:
195     bool SetString(const char* psz)
196     {
197         std::vector<unsigned char> vchTemp;
198         DecodeBase58Check(psz, vchTemp);
199         if (vchTemp.empty())
200         {
201             vchData.clear();
202             nVersion = 0;
203             return false;
204         }
205         nVersion = vchTemp[0];
206         vchData.resize(vchTemp.size() - 1);
207         if (!vchData.empty())
208             memcpy(&vchData[0], &vchTemp[1], vchData.size());
209         memset(&vchTemp[0], 0, vchTemp.size());
210         return true;
211     }
212
213     bool SetString(const std::string& str)
214     {
215         return SetString(str.c_str());
216     }
217
218     std::string ToString() const
219     {
220         std::vector<unsigned char> vch(1, nVersion);
221         vch.insert(vch.end(), vchData.begin(), vchData.end());
222         return EncodeBase58Check(vch);
223     }
224
225     int CompareTo(const CBase58Data& b58) const
226     {
227         if (nVersion < b58.nVersion) return -1;
228         if (nVersion > b58.nVersion) return  1;
229         if (vchData < b58.vchData)   return -1;
230         if (vchData > b58.vchData)   return  1;
231         return 0;
232     }
233
234     bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; }
235     bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; }
236     bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; }
237     bool operator< (const CBase58Data& b58) const { return CompareTo(b58) <  0; }
238     bool operator> (const CBase58Data& b58) const { return CompareTo(b58) >  0; }
239 };
240
241
242 class CBitcoinAddress : public CBase58Data
243 {
244 public:
245     bool SetHash160(const uint160& hash160)
246     {
247         SetData(fTestNet ? 111 : 0, &hash160, 20);
248         return true;
249     }
250
251     bool SetPubKey(const std::vector<unsigned char>& vchPubKey)
252     {
253         return SetHash160(Hash160(vchPubKey));
254     }
255
256     bool IsValid() const
257     {
258         unsigned int nExpectedSize = 20;
259         bool fExpectTestNet = false;
260         switch(nVersion)
261         {
262             case 0:
263                 break;
264
265             case 111:
266                 fExpectTestNet = true;
267                 break;
268
269             default:
270                 return false;
271         }
272         return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize;
273     }
274
275     CBitcoinAddress()
276     {
277     }
278
279     CBitcoinAddress(uint160 hash160In)
280     {
281         SetHash160(hash160In);
282     }
283
284     CBitcoinAddress(const std::vector<unsigned char>& vchPubKey)
285     {
286         SetPubKey(vchPubKey);
287     }
288
289     CBitcoinAddress(const std::string& strAddress)
290     {
291         SetString(strAddress);
292     }
293
294     CBitcoinAddress(const char* pszAddress)
295     {
296         SetString(pszAddress);
297     }
298
299     uint160 GetHash160() const
300     {
301         assert(vchData.size() == 20);
302         uint160 hash160;
303         memcpy(&hash160, &vchData[0], 20);
304         return hash160;
305     }
306 };
307
308 #endif