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.
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.
15 #ifndef BITCOIN_BASE58_H
16 #define BITCOIN_BASE58_H
24 static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
26 // Encode a byte sequence as a base58-encoded string
27 inline std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
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());
38 // Convert little endian data to bignum
42 // Convert bignum to std::string
44 // Expected size increase from base58 conversion is approximately 137%
45 // use 138% to be safe
46 str.reserve((pend - pbegin) * 138 / 100 + 1);
51 if (!BN_div(&dv, &rem, &bn, &bn58, pctx))
52 throw bignum_error("EncodeBase58 : BN_div failed");
54 unsigned int c = rem.getuint32();
58 // Leading zeroes encoded as base58 zeros
59 for (const unsigned char* p = pbegin; p < pend && *p == 0; p++)
62 // Convert little endian std::string to big endian
63 reverse(str.begin(), str.end());
67 // Encode a byte vector as a base58-encoded string
68 inline std::string EncodeBase58(const std::vector<unsigned char>& vch)
70 return EncodeBase58(&vch[0], &vch[0] + vch.size());
73 // Decode a base58-encoded string psz into byte vector vchRet
74 // returns true if decoding is successful
75 inline bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet)
85 // Convert big endian string to bignum
86 for (const char* p = psz; *p; p++)
88 const char* p1 = strchr(pszBase58, *p);
97 bnChar.setuint32(p1 - pszBase58);
98 if (!BN_mul(&bn, &bn, &bn58, pctx))
99 throw bignum_error("DecodeBase58 : BN_mul failed");
103 // Get bignum as little endian data
104 std::vector<unsigned char> vchTmp = bn.getvch();
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);
110 // Restore leading zeros
111 int nLeadingZeros = 0;
112 for (const char* p = psz; *p == pszBase58[0]; p++)
114 vchRet.assign(nLeadingZeros + vchTmp.size(), 0);
116 // Convert little endian data to big endian
117 reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size());
121 // Decode a base58-encoded string str into byte vector vchRet
122 // returns true if decoding is successful
123 inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
125 return DecodeBase58(str.c_str(), vchRet);
131 // Encode a byte vector to a base58-encoded string, including checksum
132 inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
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);
141 // Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet
142 // returns true if decoding is successful
143 inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
145 if (!DecodeBase58(psz, vchRet))
147 if (vchRet.size() < 4)
152 uint256 hash = Hash(vchRet.begin(), vchRet.end()-4);
153 if (memcmp(&hash, &vchRet.end()[-4], 4) != 0)
158 vchRet.resize(vchRet.size()-4);
162 // Decode a base58-encoded string str that includes a checksum, into byte vector vchRet
163 // returns true if decoding is successful
164 inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
166 return DecodeBase58Check(str.c_str(), vchRet);
173 /** Base class for all base58-encoded data */
178 unsigned char nVersion;
180 // the actually encoded data
181 std::vector<unsigned char> vchData;
191 // zero the memory, as it may contain sensitive data
192 if (!vchData.empty())
193 memset(&vchData[0], 0, vchData.size());
196 void SetData(int nVersionIn, const void* pdata, size_t nSize)
198 nVersion = nVersionIn;
199 vchData.resize(nSize);
200 if (!vchData.empty())
201 memcpy(&vchData[0], pdata, nSize);
204 void SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend)
206 SetData(nVersionIn, (void*)pbegin, pend - pbegin);
210 bool SetString(const char* psz)
212 std::vector<unsigned char> vchTemp;
213 DecodeBase58Check(psz, vchTemp);
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());
228 bool SetString(const std::string& str)
230 return SetString(str.c_str());
233 std::string ToString() const
235 std::vector<unsigned char> vch(1, nVersion);
236 vch.insert(vch.end(), vchData.begin(), vchData.end());
237 return EncodeBase58Check(vch);
240 int CompareTo(const CBase58Data& b58) const
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;
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; }
256 /** base58-encoded Bitcoin addresses.
257 * Public-key-hash-addresses have version 0 (or 111 testnet).
258 * The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
259 * Script-hash-addresses have version 5 (or 196 testnet).
260 * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
262 class CBitcoinAddress;
263 class CBitcoinAddressVisitor : public boost::static_visitor<bool>
266 CBitcoinAddress *addr;
268 CBitcoinAddressVisitor(CBitcoinAddress *addrIn) : addr(addrIn) { }
269 bool operator()(const CKeyID &id) const;
270 bool operator()(const CScriptID &id) const;
271 bool operator()(const CNoDestination &no) const;
274 class CBitcoinAddress : public CBase58Data
281 PUBKEY_ADDRESS_TEST = 111,
282 SCRIPT_ADDRESS_TEST = 196,
285 bool Set(const CKeyID &id) {
286 SetData(fTestNet ? PUBKEY_ADDRESS_TEST : PUBKEY_ADDRESS, &id, 20);
290 bool Set(const CScriptID &id) {
291 SetData(fTestNet ? SCRIPT_ADDRESS_TEST : SCRIPT_ADDRESS, &id, 20);
295 bool Set(const CTxDestination &dest)
297 return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
302 unsigned int nExpectedSize = 20;
303 bool fExpectTestNet = false;
307 nExpectedSize = 20; // Hash of public key
308 fExpectTestNet = false;
311 nExpectedSize = 20; // Hash of CScript
312 fExpectTestNet = false;
315 case PUBKEY_ADDRESS_TEST:
317 fExpectTestNet = true;
319 case SCRIPT_ADDRESS_TEST:
321 fExpectTestNet = true;
327 return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize;
334 CBitcoinAddress(const CTxDestination &dest)
339 CBitcoinAddress(const std::string& strAddress)
341 SetString(strAddress);
344 CBitcoinAddress(const char* pszAddress)
346 SetString(pszAddress);
349 CTxDestination Get() const {
351 return CNoDestination();
354 case PUBKEY_ADDRESS_TEST: {
356 memcpy(&id, &vchData[0], 20);
360 case SCRIPT_ADDRESS_TEST: {
362 memcpy(&id, &vchData[0], 20);
363 return CScriptID(id);
366 return CNoDestination();
369 bool GetKeyID(CKeyID &keyID) const {
374 case PUBKEY_ADDRESS_TEST: {
376 memcpy(&id, &vchData[0], 20);
380 default: return false;
384 bool IsScript() const {
389 case SCRIPT_ADDRESS_TEST: {
392 default: return false;
397 bool inline CBitcoinAddressVisitor::operator()(const CKeyID &id) const { return addr->Set(id); }
398 bool inline CBitcoinAddressVisitor::operator()(const CScriptID &id) const { return addr->Set(id); }
399 bool inline CBitcoinAddressVisitor::operator()(const CNoDestination &id) const { return false; }
401 /** A base58-encoded secret key */
402 class CBitcoinSecret : public CBase58Data
405 void SetSecret(const CSecret& vchSecret, bool fCompressed)
407 assert(vchSecret.size() == 32);
408 SetData(128 + (fTestNet ? CBitcoinAddress::PUBKEY_ADDRESS_TEST : CBitcoinAddress::PUBKEY_ADDRESS), &vchSecret[0], vchSecret.size());
410 vchData.push_back(1);
413 CSecret GetSecret(bool &fCompressedOut)
416 vchSecret.resize(32);
417 memcpy(&vchSecret[0], &vchData[0], 32);
418 fCompressedOut = vchData.size() == 33;
424 bool fExpectTestNet = false;
427 case (128 + CBitcoinAddress::PUBKEY_ADDRESS):
430 case (128 + CBitcoinAddress::PUBKEY_ADDRESS_TEST):
431 fExpectTestNet = true;
437 return fExpectTestNet == fTestNet && (vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1));
440 bool SetString(const char* pszSecret)
442 return CBase58Data::SetString(pszSecret) && IsValid();
445 bool SetString(const std::string& strSecret)
447 return SetString(strSecret.c_str());
450 CBitcoinSecret(const CSecret& vchSecret, bool fCompressed)
452 SetSecret(vchSecret, fCompressed);