Перенос данного коммита:
[novacoin.git] / src / base58.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 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 // - Double-clicking 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 <openssl/crypto.h> // for OPENSSL_cleanse()
21 #include "bignum.h"
22 #include "key.h"
23 #include "script.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.getuint32();
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 successful
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.setuint32((uint32_t)(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 successful
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 successful
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 successful
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             OPENSSL_cleanse(&vchData[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         OPENSSL_cleanse(&vchTemp[0], vchData.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 111 testnet).
259  * The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
260  * Script-hash-addresses have version 5 (or 196 testnet).
261  * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
262  */
263 class CBitcoinAddress;
264 class CBitcoinAddressVisitor : public boost::static_visitor<bool>
265 {
266 private:
267     CBitcoinAddress *addr;
268 public:
269     CBitcoinAddressVisitor(CBitcoinAddress *addrIn) : addr(addrIn) { }
270     bool operator()(const CKeyID &id) const;
271     bool operator()(const CScriptID &id) const;
272     bool operator()(const CNoDestination &no) const;
273 };
274
275 class CBitcoinAddress : public CBase58Data
276 {
277 public:
278     enum
279     {
280         PUBKEY_ADDRESS = 8,
281         SCRIPT_ADDRESS = 20,
282         PUBKEY_ADDRESS_TEST = 111,
283         SCRIPT_ADDRESS_TEST = 196,
284     };
285
286     bool Set(const CKeyID &id) {
287         SetData(fTestNet ? PUBKEY_ADDRESS_TEST : PUBKEY_ADDRESS, &id, 20);
288         return true;
289     }
290
291     bool Set(const CScriptID &id) {
292         SetData(fTestNet ? SCRIPT_ADDRESS_TEST : SCRIPT_ADDRESS, &id, 20);
293         return true;
294     }
295
296     bool Set(const CTxDestination &dest)
297     {
298         return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
299     }
300
301     bool IsValid() const
302     {
303         unsigned int nExpectedSize = 20;
304         bool fExpectTestNet = false;
305         switch(nVersion)
306         {
307             case PUBKEY_ADDRESS:
308                 nExpectedSize = 20; // Hash of public key
309                 fExpectTestNet = false;
310                 break;
311             case SCRIPT_ADDRESS:
312                 nExpectedSize = 20; // Hash of CScript
313                 fExpectTestNet = false;
314                 break;
315
316             case PUBKEY_ADDRESS_TEST:
317                 nExpectedSize = 20;
318                 fExpectTestNet = true;
319                 break;
320             case SCRIPT_ADDRESS_TEST:
321                 nExpectedSize = 20;
322                 fExpectTestNet = true;
323                 break;
324
325             default:
326                 return false;
327         }
328         return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize;
329     }
330
331     CBitcoinAddress()
332     {
333     }
334
335     CBitcoinAddress(const CTxDestination &dest)
336     {
337         Set(dest);
338     }
339
340     CBitcoinAddress(const std::string& strAddress)
341     {
342         SetString(strAddress);
343     }
344
345     CBitcoinAddress(const char* pszAddress)
346     {
347         SetString(pszAddress);
348     }
349
350     CTxDestination Get() const {
351         if (!IsValid())
352             return CNoDestination();
353         switch (nVersion) {
354         case PUBKEY_ADDRESS:
355         case PUBKEY_ADDRESS_TEST: {
356             uint160 id;
357             memcpy(&id, &vchData[0], 20);
358             return CKeyID(id);
359         }
360         case SCRIPT_ADDRESS:
361         case SCRIPT_ADDRESS_TEST: {
362             uint160 id;
363             memcpy(&id, &vchData[0], 20);
364             return CScriptID(id);
365         }
366         }
367         return CNoDestination();
368     }
369
370     bool GetKeyID(CKeyID &keyID) const {
371         if (!IsValid())
372             return false;
373         switch (nVersion) {
374         case PUBKEY_ADDRESS:
375         case PUBKEY_ADDRESS_TEST: {
376             uint160 id;
377             memcpy(&id, &vchData[0], 20);
378             keyID = CKeyID(id);
379             return true;
380         }
381         default: return false;
382         }
383     }
384
385     bool IsScript() const {
386         if (!IsValid())
387             return false;
388         switch (nVersion) {
389         case SCRIPT_ADDRESS:
390         case SCRIPT_ADDRESS_TEST: {
391             return true;
392         }
393         default: return false;
394         }
395     }
396 };
397
398 bool inline CBitcoinAddressVisitor::operator()(const CKeyID &id) const         { return addr->Set(id); }
399 bool inline CBitcoinAddressVisitor::operator()(const CScriptID &id) const      { return addr->Set(id); }
400 bool inline CBitcoinAddressVisitor::operator()(const CNoDestination &id) const { return false; }
401
402 /** A base58-encoded secret key */
403 class CBitcoinSecret : public CBase58Data
404 {
405 public:
406     void SetSecret(const CSecret& vchSecret, bool fCompressed)
407     {
408         assert(vchSecret.size() == 32);
409         SetData(128 + (fTestNet ? CBitcoinAddress::PUBKEY_ADDRESS_TEST : CBitcoinAddress::PUBKEY_ADDRESS), &vchSecret[0], vchSecret.size());
410         if (fCompressed)
411             vchData.push_back(1);
412     }
413
414     CSecret GetSecret(bool &fCompressedOut)
415     {
416         CSecret vchSecret;
417         vchSecret.resize(32);
418         memcpy(&vchSecret[0], &vchData[0], 32);
419         fCompressedOut = vchData.size() == 33;
420         return vchSecret;
421     }
422
423     bool IsValid() const
424     {
425         bool fExpectTestNet = false;
426         switch(nVersion)
427         {
428             case (128 + CBitcoinAddress::PUBKEY_ADDRESS):
429                 break;
430
431             case (128 + CBitcoinAddress::PUBKEY_ADDRESS_TEST):
432                 fExpectTestNet = true;
433                 break;
434
435             default:
436                 return false;
437         }
438         return fExpectTestNet == fTestNet && (vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1));
439     }
440
441     bool SetString(const char* pszSecret)
442     {
443         return CBase58Data::SetString(pszSecret) && IsValid();
444     }
445
446     bool SetString(const std::string& strSecret)
447     {
448         return SetString(strSecret.c_str());
449     }
450
451     CBitcoinSecret(const CSecret& vchSecret, bool fCompressed)
452     {
453         SetSecret(vchSecret, fCompressed);
454     }
455
456     CBitcoinSecret()
457     {
458     }
459 };
460
461 #endif