base58.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. // ECOin - Copyright (c) - 2014/2022 - GPLv3 - epsylon@riseup.net (https://03c8.net)
  2. #ifndef ECOIN_BASE58_H
  3. #define ECOIN_BASE58_H
  4. #include <string>
  5. #include <vector>
  6. #include "bignum.h"
  7. #include "key.h"
  8. #include "script.h"
  9. static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
  10. // Encode a byte sequence as a base58-encoded string
  11. inline std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
  12. {
  13. CAutoBN_CTX pctx;
  14. CBigNum bn58 = 58;
  15. CBigNum bn0 = 0;
  16. // Convert big endian data to little endian
  17. // Extra zero at the end make sure bignum will interpret as a positive number
  18. std::vector<unsigned char> vchTmp(pend-pbegin+1, 0);
  19. reverse_copy(pbegin, pend, vchTmp.begin());
  20. // Convert little endian data to bignum
  21. CBigNum bn;
  22. bn.setvch(vchTmp);
  23. // Convert bignum to std::string
  24. std::string str;
  25. // Expected size increase from base58 conversion is approximately 137%
  26. // use 138% to be safe
  27. str.reserve((pend - pbegin) * 138 / 100 + 1);
  28. CBigNum dv;
  29. CBigNum rem;
  30. while (bn > bn0)
  31. {
  32. if (!BN_div(&dv, &rem, &bn, &bn58, pctx))
  33. throw bignum_error("EncodeBase58 : BN_div failed");
  34. bn = dv;
  35. unsigned int c = rem.getulong();
  36. str += pszBase58[c];
  37. }
  38. // Leading zeroes encoded as base58 zeros
  39. for (const unsigned char* p = pbegin; p < pend && *p == 0; p++)
  40. str += pszBase58[0];
  41. // Convert little endian std::string to big endian
  42. reverse(str.begin(), str.end());
  43. return str;
  44. }
  45. // Encode a byte vector as a base58-encoded string
  46. inline std::string EncodeBase58(const std::vector<unsigned char>& vch)
  47. {
  48. return EncodeBase58(&vch[0], &vch[0] + vch.size());
  49. }
  50. // Decode a base58-encoded string psz into byte vector vchRet
  51. // returns true if decoding is successful
  52. inline bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet)
  53. {
  54. CAutoBN_CTX pctx;
  55. vchRet.clear();
  56. CBigNum bn58 = 58;
  57. CBigNum bn = 0;
  58. CBigNum bnChar;
  59. while (isspace(*psz))
  60. psz++;
  61. // Convert big endian string to bignum
  62. for (const char* p = psz; *p; p++)
  63. {
  64. const char* p1 = strchr(pszBase58, *p);
  65. if (p1 == NULL)
  66. {
  67. while (isspace(*p))
  68. p++;
  69. if (*p != '\0')
  70. return false;
  71. break;
  72. }
  73. bnChar.setulong(p1 - pszBase58);
  74. if (!BN_mul(&bn, &bn, &bn58, pctx))
  75. throw bignum_error("DecodeBase58 : BN_mul failed");
  76. bn += bnChar;
  77. }
  78. // Get bignum as little endian data
  79. std::vector<unsigned char> vchTmp = bn.getvch();
  80. // Trim off sign byte if present
  81. if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80)
  82. vchTmp.erase(vchTmp.end()-1);
  83. // Restore leading zeros
  84. int nLeadingZeros = 0;
  85. for (const char* p = psz; *p == pszBase58[0]; p++)
  86. nLeadingZeros++;
  87. vchRet.assign(nLeadingZeros + vchTmp.size(), 0);
  88. // Convert little endian data to big endian
  89. reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size());
  90. return true;
  91. }
  92. // Decode a base58-encoded string str into byte vector vchRet
  93. // returns true if decoding is successful
  94. inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
  95. {
  96. return DecodeBase58(str.c_str(), vchRet);
  97. }
  98. // Encode a byte vector to a base58-encoded string, including checksum
  99. inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
  100. {
  101. // add 4-byte hash check to the end
  102. std::vector<unsigned char> vch(vchIn);
  103. uint256 hash = Hash(vch.begin(), vch.end());
  104. vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
  105. return EncodeBase58(vch);
  106. }
  107. // Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet
  108. // returns true if decoding is successful
  109. inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
  110. {
  111. if (!DecodeBase58(psz, vchRet))
  112. return false;
  113. if (vchRet.size() < 4)
  114. {
  115. vchRet.clear();
  116. return false;
  117. }
  118. uint256 hash = Hash(vchRet.begin(), vchRet.end()-4);
  119. if (memcmp(&hash, &vchRet.end()[-4], 4) != 0)
  120. {
  121. vchRet.clear();
  122. return false;
  123. }
  124. vchRet.resize(vchRet.size()-4);
  125. return true;
  126. }
  127. // Decode a base58-encoded string str that includes a checksum, into byte vector vchRet
  128. // returns true if decoding is successful
  129. inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
  130. {
  131. return DecodeBase58Check(str.c_str(), vchRet);
  132. }
  133. /** Base class for all base58-encoded data */
  134. class CBase58Data
  135. {
  136. protected:
  137. // the version byte
  138. unsigned char nVersion;
  139. // the actually encoded data
  140. std::vector<unsigned char> vchData;
  141. CBase58Data()
  142. {
  143. nVersion = 0;
  144. vchData.clear();
  145. }
  146. ~CBase58Data()
  147. {
  148. // zero the memory, as it may contain sensitive data
  149. if (!vchData.empty())
  150. memset(&vchData[0], 0, vchData.size());
  151. }
  152. void SetData(int nVersionIn, const void* pdata, size_t nSize)
  153. {
  154. nVersion = nVersionIn;
  155. vchData.resize(nSize);
  156. if (!vchData.empty())
  157. memcpy(&vchData[0], pdata, nSize);
  158. }
  159. void SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend)
  160. {
  161. SetData(nVersionIn, (void*)pbegin, pend - pbegin);
  162. }
  163. public:
  164. bool SetString(const char* psz)
  165. {
  166. std::vector<unsigned char> vchTemp;
  167. DecodeBase58Check(psz, vchTemp);
  168. if (vchTemp.empty())
  169. {
  170. vchData.clear();
  171. nVersion = 0;
  172. return false;
  173. }
  174. nVersion = vchTemp[0];
  175. vchData.resize(vchTemp.size() - 1);
  176. if (!vchData.empty())
  177. memcpy(&vchData[0], &vchTemp[1], vchData.size());
  178. memset(&vchTemp[0], 0, vchTemp.size());
  179. return true;
  180. }
  181. bool SetString(const std::string& str)
  182. {
  183. return SetString(str.c_str());
  184. }
  185. std::string ToString() const
  186. {
  187. std::vector<unsigned char> vch(1, nVersion);
  188. vch.insert(vch.end(), vchData.begin(), vchData.end());
  189. return EncodeBase58Check(vch);
  190. }
  191. int CompareTo(const CBase58Data& b58) const
  192. {
  193. if (nVersion < b58.nVersion) return -1;
  194. if (nVersion > b58.nVersion) return 1;
  195. if (vchData < b58.vchData) return -1;
  196. if (vchData > b58.vchData) return 1;
  197. return 0;
  198. }
  199. bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; }
  200. bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; }
  201. bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; }
  202. bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; }
  203. bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; }
  204. };
  205. class CEcoinAddress;
  206. class CEcoinAddressVisitor : public boost::static_visitor<bool>
  207. {
  208. private:
  209. CEcoinAddress *addr;
  210. public:
  211. CEcoinAddressVisitor(CEcoinAddress *addrIn) : addr(addrIn) { }
  212. bool operator()(const CKeyID &id) const;
  213. bool operator()(const CScriptID &id) const;
  214. bool operator()(const CNoDestination &no) const;
  215. };
  216. class CEcoinAddress : public CBase58Data
  217. {
  218. public:
  219. enum
  220. {
  221. PUBKEY_ADDRESS = 33,
  222. SCRIPT_ADDRESS = 20,
  223. PUBKEY_ADDRESS_TEST = 92,
  224. SCRIPT_ADDRESS_TEST = 196,
  225. };
  226. bool Set(const CKeyID &id) {
  227. SetData(fTestNet ? PUBKEY_ADDRESS_TEST : PUBKEY_ADDRESS, &id, 20);
  228. return true;
  229. }
  230. bool Set(const CScriptID &id) {
  231. SetData(fTestNet ? SCRIPT_ADDRESS_TEST : SCRIPT_ADDRESS, &id, 20);
  232. return true;
  233. }
  234. bool Set(const CTxDestination &dest)
  235. {
  236. return boost::apply_visitor(CEcoinAddressVisitor(this), dest);
  237. }
  238. bool IsValid() const
  239. {
  240. unsigned int nExpectedSize = 20;
  241. bool fExpectTestNet = false;
  242. switch(nVersion)
  243. {
  244. case PUBKEY_ADDRESS:
  245. nExpectedSize = 20; // Hash of public key
  246. fExpectTestNet = false;
  247. break;
  248. case SCRIPT_ADDRESS:
  249. nExpectedSize = 20; // Hash of CScript
  250. fExpectTestNet = false;
  251. break;
  252. case PUBKEY_ADDRESS_TEST:
  253. nExpectedSize = 20;
  254. fExpectTestNet = true;
  255. break;
  256. case SCRIPT_ADDRESS_TEST:
  257. nExpectedSize = 20;
  258. fExpectTestNet = true;
  259. break;
  260. default:
  261. return false;
  262. }
  263. return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize;
  264. }
  265. CEcoinAddress()
  266. {
  267. }
  268. CEcoinAddress(const CTxDestination &dest)
  269. {
  270. Set(dest);
  271. }
  272. CEcoinAddress(const std::string& strAddress)
  273. {
  274. SetString(strAddress);
  275. }
  276. CEcoinAddress(const char* pszAddress)
  277. {
  278. SetString(pszAddress);
  279. }
  280. CTxDestination Get() const {
  281. if (!IsValid())
  282. return CNoDestination();
  283. switch (nVersion) {
  284. case PUBKEY_ADDRESS:
  285. case PUBKEY_ADDRESS_TEST: {
  286. uint160 id;
  287. memcpy(&id, &vchData[0], 20);
  288. return CKeyID(id);
  289. }
  290. case SCRIPT_ADDRESS:
  291. case SCRIPT_ADDRESS_TEST: {
  292. uint160 id;
  293. memcpy(&id, &vchData[0], 20);
  294. return CScriptID(id);
  295. }
  296. }
  297. return CNoDestination();
  298. }
  299. bool GetKeyID(CKeyID &keyID) const {
  300. if (!IsValid())
  301. return false;
  302. switch (nVersion) {
  303. case PUBKEY_ADDRESS:
  304. case PUBKEY_ADDRESS_TEST: {
  305. uint160 id;
  306. memcpy(&id, &vchData[0], 20);
  307. keyID = CKeyID(id);
  308. return true;
  309. }
  310. default: return false;
  311. }
  312. }
  313. bool IsScript() const {
  314. if (!IsValid())
  315. return false;
  316. switch (nVersion) {
  317. case SCRIPT_ADDRESS:
  318. case SCRIPT_ADDRESS_TEST: {
  319. return true;
  320. }
  321. default: return false;
  322. }
  323. }
  324. };
  325. bool inline CEcoinAddressVisitor::operator()(const CKeyID &id) const { return addr->Set(id); }
  326. bool inline CEcoinAddressVisitor::operator()(const CScriptID &id) const { return addr->Set(id); }
  327. bool inline CEcoinAddressVisitor::operator()(const CNoDestination &id) const { return false; }
  328. /** A base58-encoded secret key */
  329. class CEcoinSecret : public CBase58Data
  330. {
  331. public:
  332. void SetSecret(const CSecret& vchSecret, bool fCompressed)
  333. {
  334. assert(vchSecret.size() == 32);
  335. SetData(128 + (fTestNet ? CEcoinAddress::PUBKEY_ADDRESS_TEST : CEcoinAddress::PUBKEY_ADDRESS), &vchSecret[0], vchSecret.size());
  336. if (fCompressed)
  337. vchData.push_back(1);
  338. }
  339. CSecret GetSecret(bool &fCompressedOut)
  340. {
  341. CSecret vchSecret;
  342. vchSecret.resize(32);
  343. memcpy(&vchSecret[0], &vchData[0], 32);
  344. fCompressedOut = vchData.size() == 33;
  345. return vchSecret;
  346. }
  347. bool IsValid() const
  348. {
  349. bool fExpectTestNet = false;
  350. switch(nVersion)
  351. {
  352. case (128 + CEcoinAddress::PUBKEY_ADDRESS):
  353. break;
  354. case (128 + CEcoinAddress::PUBKEY_ADDRESS_TEST):
  355. fExpectTestNet = true;
  356. break;
  357. default:
  358. return false;
  359. }
  360. return fExpectTestNet == fTestNet && (vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1));
  361. }
  362. bool SetString(const char* pszSecret)
  363. {
  364. return CBase58Data::SetString(pszSecret) && IsValid();
  365. }
  366. bool SetString(const std::string& strSecret)
  367. {
  368. return SetString(strSecret.c_str());
  369. }
  370. CEcoinSecret(const CSecret& vchSecret, bool fCompressed)
  371. {
  372. SetSecret(vchSecret, fCompressed);
  373. }
  374. CEcoinSecret()
  375. {
  376. }
  377. };
  378. #endif