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
21 #include "chainparams.h"
25 #include "allocators.h"
27 static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
29 // Encode a byte sequence as a base58-encoded string
30 inline std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
36 // Convert big endian data to little endian
37 // Extra zero at the end make sure bignum will interpret as a positive number
38 std::vector<unsigned char> vchTmp(pend-pbegin+1, 0);
39 reverse_copy(pbegin, pend, vchTmp.begin());
41 // Convert little endian data to bignum
45 // Convert bignum to std::string
47 // Expected size increase from base58 conversion is approximately 137%
48 // use 138% to be safe
49 str.reserve((pend - pbegin) * 138 / 100 + 1);
54 if (!BN_div(&dv, &rem, &bn, &bn58, pctx))
55 throw bignum_error("EncodeBase58 : BN_div failed");
57 unsigned int c = rem.getulong();
61 // Leading zeroes encoded as base58 zeros
62 for (const unsigned char* p = pbegin; p < pend && *p == 0; p++)
65 // Convert little endian std::string to big endian
66 reverse(str.begin(), str.end());
70 // Encode a byte vector as a base58-encoded string
71 inline std::string EncodeBase58(const std::vector<unsigned char>& vch)
73 return EncodeBase58(&vch[0], &vch[0] + vch.size());
76 // Decode a base58-encoded string psz into byte vector vchRet
77 // returns true if decoding is successful
78 inline bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet)
88 // Convert big endian string to bignum
89 for (const char* p = psz; *p; p++)
91 const char* p1 = strchr(pszBase58, *p);
100 bnChar.setulong(p1 - pszBase58);
101 if (!BN_mul(&bn, &bn, &bn58, pctx))
102 throw bignum_error("DecodeBase58 : BN_mul failed");
106 // Get bignum as little endian data
107 std::vector<unsigned char> vchTmp = bn.getvch();
109 // Trim off sign byte if present
110 if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80)
111 vchTmp.erase(vchTmp.end()-1);
113 // Restore leading zeros
114 int nLeadingZeros = 0;
115 for (const char* p = psz; *p == pszBase58[0]; p++)
117 vchRet.assign(nLeadingZeros + vchTmp.size(), 0);
119 // Convert little endian data to big endian
120 reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size());
124 // Decode a base58-encoded string str into byte vector vchRet
125 // returns true if decoding is successful
126 inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
128 return DecodeBase58(str.c_str(), vchRet);
134 // Encode a byte vector to a base58-encoded string, including checksum
135 inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
137 // add 4-byte hash check to the end
138 std::vector<unsigned char> vch(vchIn);
139 uint256 hash = Hash(vch.begin(), vch.end());
140 vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
141 return EncodeBase58(vch);
144 // Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet
145 // returns true if decoding is successful
146 inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
148 if (!DecodeBase58(psz, vchRet))
150 if (vchRet.size() < 4)
155 uint256 hash = Hash(vchRet.begin(), vchRet.end()-4);
156 if (memcmp(&hash, &vchRet.end()[-4], 4) != 0)
161 vchRet.resize(vchRet.size()-4);
165 // Decode a base58-encoded string str that includes a checksum, into byte vector vchRet
166 // returns true if decoding is successful
167 inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
169 return DecodeBase58Check(str.c_str(), vchRet);
176 /** Base class for all base58-encoded data */
180 // the version byte(s)
181 std::vector<unsigned char> vchVersion;
183 // the actually encoded data
184 typedef std::vector<unsigned char, zero_after_free_allocator<unsigned char> > vector_uchar;
185 vector_uchar vchData;
193 void SetData(const std::vector<unsigned char> &vchVersionIn, const void* pdata, size_t nSize)
195 vchVersion = vchVersionIn;
196 vchData.resize(nSize);
197 if (!vchData.empty())
198 memcpy(&vchData[0], pdata, nSize);
201 void SetData(const std::vector<unsigned char> &vchVersionIn, const unsigned char *pbegin, const unsigned char *pend)
203 SetData(vchVersionIn, (void*)pbegin, pend - pbegin);
207 bool SetString(const char* psz, unsigned int nVersionBytes = 1)
209 std::vector<unsigned char> vchTemp;
210 DecodeBase58Check(psz, vchTemp);
211 if (vchTemp.size() < nVersionBytes)
217 vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);
218 vchData.resize(vchTemp.size() - nVersionBytes);
219 if (!vchData.empty())
220 memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size());
221 OPENSSL_cleanse(&vchTemp[0], vchData.size());
225 bool SetString(const std::string& str)
227 return SetString(str.c_str());
230 std::string ToString() const
232 std::vector<unsigned char> vch = vchVersion;
233 vch.insert(vch.end(), vchData.begin(), vchData.end());
234 return EncodeBase58Check(vch);
237 int CompareTo(const CBase58Data& b58) const
239 if (vchVersion < b58.vchVersion) return -1;
240 if (vchVersion > b58.vchVersion) return 1;
241 if (vchData < b58.vchData) return -1;
242 if (vchData > b58.vchData) return 1;
246 bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; }
247 bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; }
248 bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; }
249 bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; }
250 bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; }
253 /** base58-encoded Bitcoin addresses.
254 * Public-key-hash-addresses have version 0 (or 111 testnet).
255 * The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
256 * Script-hash-addresses have version 5 (or 196 testnet).
257 * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
259 class CBitcoinAddress;
260 class CBitcoinAddressVisitor : public boost::static_visitor<bool>
263 CBitcoinAddress *addr;
265 CBitcoinAddressVisitor(CBitcoinAddress *addrIn) : addr(addrIn) { }
266 bool operator()(const CKeyID &id) const;
267 bool operator()(const CScriptID &id) const;
268 bool operator()(const CNoDestination &no) const;
271 class CBitcoinAddress : public CBase58Data
274 bool Set(const CKeyID &id) {
275 SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);
279 bool Set(const CScriptID &id) {
280 SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);
284 bool Set(const CTxDestination &dest)
286 return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
291 bool fCorrectSize = vchData.size() == 20;
292 bool fKnownVersion = vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
293 vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
294 return fCorrectSize && fKnownVersion;
301 CBitcoinAddress(const CTxDestination &dest)
306 CBitcoinAddress(const std::string& strAddress)
308 SetString(strAddress);
311 CBitcoinAddress(const char* pszAddress)
313 SetString(pszAddress);
316 CTxDestination Get() const {
318 return CNoDestination();
320 memcpy(&id, &vchData[0], 20);
321 if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
323 else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))
324 return CScriptID(id);
326 return CNoDestination();
329 bool GetKeyID(CKeyID &keyID) const {
330 if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
333 memcpy(&id, &vchData[0], 20);
338 bool IsScript() const {
339 return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
343 bool inline CBitcoinAddressVisitor::operator()(const CKeyID &id) const { return addr->Set(id); }
344 bool inline CBitcoinAddressVisitor::operator()(const CScriptID &id) const { return addr->Set(id); }
345 bool inline CBitcoinAddressVisitor::operator()(const CNoDestination &id) const { return false; }
347 /** A base58-encoded secret key */
348 class CBitcoinSecret : public CBase58Data
351 void SetKey(const CKey& vchSecret)
353 assert(vchSecret.IsValid());
354 SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
355 if (vchSecret.IsCompressed())
356 vchData.push_back(1);
362 ret.Set(&vchData[0], &vchData[32], vchData.size() > 32 && vchData[32] == 1);
368 bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);
369 bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY);
370 return fExpectedFormat && fCorrectVersion;
373 bool SetString(const char* pszSecret)
375 return CBase58Data::SetString(pszSecret) && IsValid();
378 bool SetString(const std::string& strSecret)
380 return SetString(strSecret.c_str());
383 CBitcoinSecret(const CKey& vchSecret)
394 template<typename K, int Size, CChainParams::Base58Type Type> class CBitcoinExtKeyBase : public CBase58Data
397 void SetKey(const K &key) {
398 unsigned char vch[Size];
400 SetData(Params().Base58Prefix(Type), vch, vch+Size);
405 ret.Decode(&vchData[0], &vchData[Size]);
409 CBitcoinExtKeyBase(const K &key) {
413 CBitcoinExtKeyBase() {}
416 typedef CBitcoinExtKeyBase<CExtKey, 74, CChainParams::EXT_SECRET_KEY> CBitcoinExtKey;
417 typedef CBitcoinExtKeyBase<CExtPubKey, 74, CChainParams::EXT_PUBLIC_KEY> CBitcoinExtPubKey;
419 #endif // BITCOIN_BASE58_H