1 // Copyright (c) 2014 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
15 #include <boost/variant/apply_visitor.hpp>
16 #include <boost/variant/static_visitor.hpp>
18 /** All alphanumeric characters except for "0", "I", "O", and "l" */
19 static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
21 bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
23 // Skip leading spaces.
24 while (*psz && isspace(*psz))
26 // Skip and count leading '1's.
32 // Allocate enough space in big-endian base256 representation.
33 std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up.
34 // Process the characters.
35 while (*psz && !isspace(*psz)) {
36 // Decode base58 character
37 const char* ch = strchr(pszBase58, *psz);
40 // Apply "b256 = b256 * 58 + ch".
41 int carry = ch - pszBase58;
42 for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {
50 // Skip trailing spaces.
55 // Skip leading zeroes in b256.
56 std::vector<unsigned char>::iterator it = b256.begin();
57 while (it != b256.end() && *it == 0)
59 // Copy result into output vector.
60 vch.reserve(zeroes + (b256.end() - it));
61 vch.assign(zeroes, 0x00);
62 while (it != b256.end())
63 vch.push_back(*(it++));
67 std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
69 // Skip & count leading zeroes.
71 while (pbegin != pend && *pbegin == 0) {
75 // Allocate enough space in big-endian base58 representation.
76 std::vector<unsigned char> b58((pend - pbegin) * 138 / 100 + 1); // log(256) / log(58), rounded up.
78 while (pbegin != pend) {
80 // Apply "b58 = b58 * 256 + ch".
81 for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); it != b58.rend(); it++) {
89 // Skip leading zeroes in base58 result.
90 std::vector<unsigned char>::iterator it = b58.begin();
91 while (it != b58.end() && *it == 0)
93 // Translate the result into a string.
95 str.reserve(zeroes + (b58.end() - it));
96 str.assign(zeroes, '1');
97 while (it != b58.end())
98 str += pszBase58[*(it++)];
102 std::string EncodeBase58(const std::vector<unsigned char>& vch)
104 return EncodeBase58(vch.data(), vch.data() + vch.size());
107 bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
109 return DecodeBase58(str.c_str(), vchRet);
112 std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
114 // add 4-byte hash check to the end
115 std::vector<unsigned char> vch(vchIn);
116 uint256 hash = Hash(vch.begin(), vch.end());
117 vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
118 return EncodeBase58(vch);
121 bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
123 if (!DecodeBase58(psz, vchRet) ||
124 (vchRet.size() < 4)) {
128 // re-calculate the checksum, insure it matches the included 4-byte checksum
129 uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);
130 if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {
134 vchRet.resize(vchRet.size() - 4);
138 bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
140 return DecodeBase58Check(str.c_str(), vchRet);
144 CBase58Data::CBase58Data()
150 void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)
152 vchVersion = vchVersionIn;
153 vchData.resize(nSize);
154 if (!vchData.empty())
155 memcpy(&vchData[0], pdata, nSize);
158 void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)
160 SetData(vchVersionIn, (void*)pbegin, pend - pbegin);
163 bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)
165 std::vector<unsigned char> vchTemp;
166 bool rc58 = DecodeBase58Check(psz, vchTemp);
167 if ((!rc58) || (vchTemp.size() < nVersionBytes)) {
172 vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);
173 vchData.resize(vchTemp.size() - nVersionBytes);
174 if (!vchData.empty())
175 memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size());
176 memory_cleanse(&vchTemp[0], vchData.size());
180 bool CBase58Data::SetString(const std::string& str, unsigned int nVersionBytes)
182 return SetString(str.c_str(), nVersionBytes);
185 std::string CBase58Data::ToString() const
187 std::vector<unsigned char> vch = vchVersion;
188 vch.insert(vch.end(), vchData.begin(), vchData.end());
189 return EncodeBase58Check(vch);
192 int CBase58Data::CompareTo(const CBase58Data& b58) const
194 if (vchVersion < b58.vchVersion)
196 if (vchVersion > b58.vchVersion)
198 if (vchData < b58.vchData)
200 if (vchData > b58.vchData)
207 class CBitcoinAddressVisitor : public boost::static_visitor<bool>
210 CBitcoinAddress* addr;
213 CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {}
215 bool operator()(const CKeyID& id) const { return addr->Set(id); }
216 bool operator()(const CPubKey& key) const { return addr->Set(key); }
217 bool operator()(const CScriptID& id) const { return addr->Set(id); }
218 bool operator()(const CNoDestination& no) const { return false; }
223 bool CBitcoinAddress::Set(const CKeyID& id)
225 SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);
229 bool CBitcoinAddress::Set(const CPubKey& key)
231 CKeyID id = key.GetID();
232 SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);
236 bool CBitcoinAddress::Set(const CScriptID& id)
238 SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);
242 bool CBitcoinAddress::Set(const CTxDestination& dest)
244 return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
247 bool CBitcoinAddress::IsValid() const
249 return IsValid(Params());
252 bool CBitcoinAddress::IsValid(const CChainParams& params) const
254 bool fCorrectSize = vchData.size() == 20;
255 bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
256 vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
257 return fCorrectSize && fKnownVersion;
260 bool CBitcoinAddress::SetString(const char* pszAddress)
262 return CBase58Data::SetString(pszAddress, 1);//2);
265 bool CBitcoinAddress::SetString(const std::string& strAddress)
267 return SetString(strAddress.c_str());
270 CTxDestination CBitcoinAddress::Get() const
273 return CNoDestination();
275 memcpy(&id, &vchData[0], 20);
276 if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
278 else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))
279 return CScriptID(id);
281 return CNoDestination();
284 bool CBitcoinAddress::GetIndexKey(uint160& hashBytes, int& type) const
288 } else if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) {
289 memcpy(&hashBytes, &vchData[0], 20);
292 } else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS)) {
293 memcpy(&hashBytes, &vchData[0], 20);
301 bool CBitcoinAddress::GetKeyID(CKeyID& keyID) const
303 if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
306 memcpy(&id, &vchData[0], 20);
311 bool CBitcoinAddress::GetKeyID_NoCheck(CKeyID& keyID) const
314 memcpy(&id, &vchData[0], 20);
319 bool CBitcoinAddress::IsScript() const
321 return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
324 void CBitcoinSecret::SetKey(const CKey& vchSecret)
326 assert(vchSecret.IsValid());
327 SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
328 if (vchSecret.IsCompressed())
329 vchData.push_back(1);
332 CKey CBitcoinSecret::GetKey()
335 assert(vchData.size() >= 32);
336 ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);
340 bool CBitcoinSecret::IsValid() const
342 bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);
343 bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY);
344 return fExpectedFormat && fCorrectVersion;
347 bool CBitcoinSecret::SetString(const char* pszSecret)
349 return CBase58Data::SetString(pszSecret, 1) && IsValid();
352 bool CBitcoinSecret::SetString(const std::string& strSecret)
354 return SetString(strSecret.c_str());
357 template<class DATA_TYPE, CChainParams::Base58Type PREFIX, size_t SER_SIZE>
358 bool CZCEncoding<DATA_TYPE, PREFIX, SER_SIZE>::Set(const DATA_TYPE& addr)
360 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
362 std::vector<unsigned char> addrSerialized(ss.begin(), ss.end());
363 assert(addrSerialized.size() == SER_SIZE);
364 SetData(Params().Base58Prefix(PREFIX), &addrSerialized[0], SER_SIZE);
368 template<class DATA_TYPE, CChainParams::Base58Type PREFIX, size_t SER_SIZE>
369 DATA_TYPE CZCEncoding<DATA_TYPE, PREFIX, SER_SIZE>::Get() const
371 if (vchData.size() != SER_SIZE) {
372 throw std::runtime_error(
373 PrependName(" is invalid")
377 if (vchVersion != Params().Base58Prefix(PREFIX)) {
378 throw std::runtime_error(
379 PrependName(" is for wrong network type")
383 std::vector<unsigned char> serialized(vchData.begin(), vchData.end());
385 CDataStream ss(serialized, SER_NETWORK, PROTOCOL_VERSION);