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