Back to home page

Bitcoin sources

 
 

    


File indexing completed on 2020-06-25 15:53:36

0001 // Copyright (c) 2009-2010 Satoshi Nakamoto
0002 // Copyright (c) 2009-2012 The Bitcoin developers
0003 // Distributed under the MIT/X11 software license, see the accompanying
0004 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
0005 #ifndef BITCOIN_UTIL_H
0006 #define BITCOIN_UTIL_H
0007 
0008 #include "uint256.h"
0009 
0010 #include <stdint.h>
0011 #include <sys/types.h>
0012 #include <sys/time.h>
0013 #include <sys/resource.h>
0014 #include <map>
0015 #include <vector>
0016 #include <string>
0017 
0018 #include <boost/thread.hpp>
0019 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
0020 #include <boost/date_time/gregorian/gregorian_types.hpp>
0021 #include <boost/date_time/posix_time/posix_time_types.hpp>
0022 
0023 #include <openssl/sha.h>
0024 #include <openssl/ripemd.h>
0025 
0026 
0027 typedef long long  int64;
0028 typedef unsigned long long  uint64;
0029 
0030 #define __forceinline  inline
0031 
0032 #define loop                for (;;)
0033 #define BEGIN(a)            ((char*)&(a))
0034 #define END(a)              ((char*)&((&(a))[1]))
0035 #define UBEGIN(a)           ((unsigned char*)&(a))
0036 #define UEND(a)             ((unsigned char*)&((&(a))[1]))
0037 #define ARRAYLEN(array)     (sizeof(array)/sizeof((array)[0]))
0038 #define printf              OutputDebugStringF
0039 
0040 #ifdef snprintf
0041 #undef snprintf
0042 #endif
0043 #define snprintf my_snprintf
0044 
0045 #ifndef PRI64d
0046 #define PRI64d  "lld"
0047 #define PRI64u  "llu"
0048 #define PRI64x  "llx"
0049 #endif
0050 
0051 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
0052 #define PAIRTYPE(t1, t2)    std::pair<t1, t2>
0053 
0054 // Align by increasing pointer, must have extra space at end of buffer
0055 template <size_t nBytes, typename T>
0056 T* alignup(T* p)
0057 {
0058     union
0059     {
0060         T* ptr;
0061         size_t n;
0062     } u;
0063     u.ptr = p;
0064     u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
0065     return u.ptr;
0066 }
0067 
0068 #define WSAGetLastError()   errno
0069 #define WSAEINVAL           EINVAL
0070 #define WSAEALREADY         EALREADY
0071 #define WSAEWOULDBLOCK      EWOULDBLOCK
0072 #define WSAEMSGSIZE         EMSGSIZE
0073 #define WSAEINTR            EINTR
0074 #define WSAEINPROGRESS      EINPROGRESS
0075 #define WSAEADDRINUSE       EADDRINUSE
0076 #define WSAENOTSOCK         EBADF
0077 #define INVALID_SOCKET      (SOCKET)(~0)
0078 #define SOCKET_ERROR        -1
0079 typedef u_int SOCKET;
0080 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
0081 #define strlwr(psz)         to_lower(psz)
0082 #define _strlwr(psz)        to_lower(psz)
0083 #define MAX_PATH            1024
0084 #define Beep(n1,n2)         (0)
0085 inline void Sleep(int64 n)
0086 {
0087     /*Boost has a year 2038 problem- if the request sleep time is past epoch+2^31 seconds the sleep returns instantly.
0088       So we clamp our sleeps here to 10 years and hope that boost is fixed by 2028.*/
0089     boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n>315576000000LL?315576000000LL:n));
0090 }
0091 
0092 
0093 inline int myclosesocket(SOCKET& hSocket)
0094 {
0095     if (hSocket == INVALID_SOCKET)
0096         return WSAENOTSOCK;
0097     int ret = close(hSocket);
0098     hSocket = INVALID_SOCKET;
0099     return ret;
0100 }
0101 #define closesocket(s)      myclosesocket(s)
0102 inline const char* _(const char* psz)
0103 {
0104     return psz;
0105 }
0106 
0107 
0108 extern std::map<std::string, std::string> mapArgs;
0109 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
0110 extern bool fDebug;
0111 extern bool fPrintToConsole;
0112 extern bool fPrintToDebugger;
0113 extern bool fCanEat;
0114 extern bool fVerifyAll;
0115 extern char pszSetDataDir[MAX_PATH];
0116 extern bool fRequestShutdown;
0117 extern bool fShutdown;
0118 extern bool fDaemon;
0119 extern bool fServer;
0120 extern bool fCommandLine;
0121 extern std::string strMiscWarning;
0122 extern bool fNoListen;
0123 extern bool fLogTimestamps;
0124 
0125 void RandAddSeed();
0126 void RandAddSeedPerfmon();
0127 int OutputDebugStringF(const char* pszFormat, ...);
0128 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
0129 std::string strprintf(const std::string &format, ...);
0130 bool error(const std::string &format, ...);
0131 void LogException(std::exception* pex, const char* pszThread);
0132 void PrintException(std::exception* pex, const char* pszThread);
0133 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
0134 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
0135 std::string FormatMoney(int64 n, bool fPlus=false);
0136 bool ParseMoney(const std::string& str, int64& nRet);
0137 bool ParseMoney(const char* pszIn, int64& nRet);
0138 std::vector<unsigned char> ParseHex(const char* psz);
0139 std::vector<unsigned char> ParseHex(const std::string& str);
0140 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
0141 std::string DecodeBase64(const std::string& str);
0142 std::string EncodeBase64(const unsigned char* pch, size_t len);
0143 std::string EncodeBase64(const std::string& str);
0144 void ParseParameters(int argc, char* argv[]);
0145 const char* wxGetTranslation(const char* psz);
0146 bool WildcardMatch(const char* psz, const char* mask);
0147 bool WildcardMatch(const std::string& str, const std::string& mask);
0148 int GetFilesize(FILE* file);
0149 void GetDataDir(char* pszDirRet);
0150 std::string GetConfigFile();
0151 std::string GetPidFile();
0152 void CreatePidFile(std::string pidFile, pid_t pid);
0153 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
0154 std::string GetDefaultDataDir();
0155 std::string GetDataDir();
0156 void ShrinkDebugFile();
0157 int GetRandInt(int nMax);
0158 uint64 GetRand(uint64 nMax);
0159 int64 GetTime();
0160 void SetMockTime(int64 nMockTimeIn);
0161 int64 GetAdjustedTime();
0162 void AddTimeData(unsigned int ip, int64 nTime);
0163 std::string FormatFullVersion();
0164 
0165 
0166 
0167 
0168 
0169 
0170 
0171 
0172 
0173 
0174 
0175 
0176 
0177 // Wrapper to automatically initialize mutex
0178 class CCriticalSection
0179 {
0180 protected:
0181     boost::interprocess::interprocess_recursive_mutex mutex;
0182 public:
0183     explicit CCriticalSection() { }
0184     ~CCriticalSection() { }
0185     void Enter(const char* pszName, const char* pszFile, int nLine);
0186     void Leave();
0187     bool TryEnter(const char* pszName, const char* pszFile, int nLine);
0188 };
0189 
0190 // Automatically leave critical section when leaving block, needed for exception safety
0191 class CCriticalBlock
0192 {
0193 protected:
0194     CCriticalSection* pcs;
0195 
0196 public:
0197     CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
0198     {
0199         pcs = &csIn;
0200         pcs->Enter(pszName, pszFile, nLine);
0201     }
0202 
0203     operator bool() const
0204     {
0205         return true;
0206     }
0207 
0208     ~CCriticalBlock()
0209     {
0210         pcs->Leave();
0211     }
0212 };
0213 
0214 #define CRITICAL_BLOCK(cs)     \
0215     if (CCriticalBlock criticalblock = CCriticalBlock(cs, #cs, __FILE__, __LINE__))
0216 
0217 #define ENTER_CRITICAL_SECTION(cs) \
0218     (cs).Enter(#cs, __FILE__, __LINE__)
0219 
0220 #define LEAVE_CRITICAL_SECTION(cs) \
0221     (cs).Leave()
0222 
0223 class CTryCriticalBlock
0224 {
0225 protected:
0226     CCriticalSection* pcs;
0227 
0228 public:
0229     CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
0230     {
0231         pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
0232     }
0233 
0234     operator bool() const
0235     {
0236         return Entered();
0237     }
0238 
0239     ~CTryCriticalBlock()
0240     {
0241         if (pcs)
0242         {
0243             pcs->Leave();
0244         }
0245     }
0246     bool Entered() const { return pcs != NULL; }
0247 };
0248 
0249 #define TRY_CRITICAL_BLOCK(cs)     \
0250     if (CTryCriticalBlock criticalblock = CTryCriticalBlock(cs, #cs, __FILE__, __LINE__))
0251 
0252 
0253 
0254 
0255 
0256 
0257 // This is exactly like std::string, but with a custom allocator.
0258 // (secure_allocator<> is defined in serialize.h)
0259 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
0260 
0261 // This is exactly like std::string, but with a custom allocator.
0262 // (secure_allocator<> is defined in serialize.h)
0263 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
0264 
0265 
0266 
0267 
0268 
0269 inline std::string i64tostr(int64 n)
0270 {
0271     return strprintf("%"PRI64d, n);
0272 }
0273 
0274 inline std::string itostr(int n)
0275 {
0276     return strprintf("%d", n);
0277 }
0278 
0279 inline int64 atoi64(const char* psz)
0280 {
0281     return strtoll(psz, NULL, 10);
0282 }
0283 
0284 inline int64 atoi64(const std::string& str)
0285 {
0286     return strtoll(str.c_str(), NULL, 10);
0287 }
0288 
0289 inline int atoi(const std::string& str)
0290 {
0291     return atoi(str.c_str());
0292 }
0293 
0294 inline int roundint(double d)
0295 {
0296     return (int)(d > 0 ? d + 0.5 : d - 0.5);
0297 }
0298 
0299 inline int64 roundint64(double d)
0300 {
0301     return (int64)(d > 0 ? d + 0.5 : d - 0.5);
0302 }
0303 
0304 inline int64 abs64(int64 n)
0305 {
0306     return (n >= 0 ? n : -n);
0307 }
0308 
0309 template<typename T>
0310 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
0311 {
0312     if (itbegin == itend)
0313         return "";
0314     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
0315     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
0316     std::string str;
0317     str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
0318     for (const unsigned char* p = pbegin; p != pend; p++)
0319         str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
0320     return str;
0321 }
0322 
0323 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
0324 {
0325     return HexStr(vch.begin(), vch.end(), fSpaces);
0326 }
0327 
0328 template<typename T>
0329 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
0330 {
0331     if (itbegin == itend)
0332         return "";
0333     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
0334     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
0335     std::string str = (f0x ? "0x" : "");
0336     str.reserve(str.size() + (pend-pbegin) * 2);
0337     for (const unsigned char* p = pend-1; p >= pbegin; p--)
0338         str += strprintf("%02x", *p);
0339     return str;
0340 }
0341 
0342 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
0343 {
0344     return HexNumStr(vch.begin(), vch.end(), f0x);
0345 }
0346 
0347 template<typename T>
0348 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
0349 {
0350     printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
0351 }
0352 
0353 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
0354 {
0355     printf(pszFormat, HexStr(vch, fSpaces).c_str());
0356 }
0357 
0358 inline int64 GetPerformanceCounter()
0359 {
0360     int64 nCounter = 0;
0361     timeval t;
0362     gettimeofday(&t, NULL);
0363     nCounter = t.tv_sec * 1000000 + t.tv_usec;
0364     return nCounter;
0365 }
0366 
0367 inline int64 GetTimeMillis()
0368 {
0369     return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
0370             boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
0371 }
0372 
0373 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
0374 {
0375     time_t n = nTime;
0376     struct tm* ptmTime = gmtime(&n);
0377     char pszTime[200];
0378     strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
0379     return pszTime;
0380 }
0381 
0382 template<typename T>
0383 void skipspaces(T& it)
0384 {
0385     while (isspace(*it))
0386         ++it;
0387 }
0388 
0389 inline bool IsSwitchChar(char c)
0390 {
0391     return c == '-';
0392 }
0393 
0394 inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
0395 {
0396     if (mapArgs.count(strArg))
0397         return mapArgs[strArg];
0398     return strDefault;
0399 }
0400 
0401 inline int64 GetArg(const std::string& strArg, int64 nDefault)
0402 {
0403     if (mapArgs.count(strArg))
0404         return atoi64(mapArgs[strArg]);
0405     return nDefault;
0406 }
0407 
0408 inline bool GetBoolArg(const std::string& strArg, bool fDefault=false)
0409 {
0410     if (mapArgs.count(strArg))
0411     {
0412         if (mapArgs[strArg].empty())
0413             return true;
0414         return (atoi(mapArgs[strArg]) != 0);
0415     }
0416     return fDefault;
0417 }
0418 
0419 /**
0420  * Set an argument if it doesn't already have a value
0421  *
0422  * @param strArg Argument to set (e.g. "-foo")
0423  * @param strValue Value (e.g. "1")
0424  * @return true if argument gets set, false if it already had a value
0425  */
0426 bool SoftSetArg(const std::string& strArg, const std::string& strValue);
0427 
0428 /**
0429  * Set a boolean argument if it doesn't already have a value
0430  *
0431  * @param strArg Argument to set (e.g. "-foo")
0432  * @param fValue Value (e.g. false)
0433  * @return true if argument gets set, false if it already had a value
0434  */
0435 bool SoftSetArg(const std::string& strArg, bool fValue);
0436 
0437 
0438 
0439 
0440 
0441 
0442 
0443 
0444 
0445 inline void heapchk()
0446 {
0447 }
0448 
0449 // Randomize the stack to help protect against buffer overrun exploits
0450 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn)     \
0451     {                                           \
0452         static char nLoops;                     \
0453         if (nLoops <= 0)                        \
0454             nLoops = GetRand(20) + 1;           \
0455         if (nLoops-- > 1)                       \
0456         {                                       \
0457             ThreadFn;                           \
0458             return;                             \
0459         }                                       \
0460     }
0461 
0462 #define CATCH_PRINT_EXCEPTION(pszFn)     \
0463     catch (std::exception& e) {          \
0464         PrintException(&e, (pszFn));     \
0465     } catch (...) {                      \
0466         PrintException(NULL, (pszFn));   \
0467     }
0468 
0469 
0470 
0471 
0472 
0473 
0474 
0475 
0476 
0477 
0478 template<typename T1>
0479 inline uint256 Hash(const T1 pbegin, const T1 pend)
0480 {
0481     static unsigned char pblank[1];
0482     uint256 hash1;
0483     SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
0484     uint256 hash2;
0485     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
0486     return hash2;
0487 }
0488 
0489 template<typename T1, typename T2>
0490 inline uint256 Hash(const T1 p1begin, const T1 p1end,
0491                     const T2 p2begin, const T2 p2end)
0492 {
0493     static unsigned char pblank[1];
0494     uint256 hash1;
0495     SHA256_CTX ctx;
0496     SHA256_Init(&ctx);
0497     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
0498     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
0499     SHA256_Final((unsigned char*)&hash1, &ctx);
0500     uint256 hash2;
0501     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
0502     return hash2;
0503 }
0504 
0505 template<typename T1, typename T2, typename T3>
0506 inline uint256 Hash(const T1 p1begin, const T1 p1end,
0507                     const T2 p2begin, const T2 p2end,
0508                     const T3 p3begin, const T3 p3end)
0509 {
0510     static unsigned char pblank[1];
0511     uint256 hash1;
0512     SHA256_CTX ctx;
0513     SHA256_Init(&ctx);
0514     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
0515     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
0516     SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
0517     SHA256_Final((unsigned char*)&hash1, &ctx);
0518     uint256 hash2;
0519     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
0520     return hash2;
0521 }
0522 
0523 template<typename T>
0524 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
0525 {
0526     // Most of the time is spent allocating and deallocating CDataStream's
0527     // buffer.  If this ever needs to be optimized further, make a CStaticStream
0528     // class with its buffer on the stack.
0529     CDataStream ss(nType, nVersion);
0530     ss.reserve(10000);
0531     ss << obj;
0532     return Hash(ss.begin(), ss.end());
0533 }
0534 
0535 inline uint160 Hash160(const std::vector<unsigned char>& vch)
0536 {
0537     uint256 hash1;
0538     SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
0539     uint160 hash2;
0540     RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
0541     return hash2;
0542 }
0543 
0544 
0545 // Median filter over a stream of values
0546 // Returns the median of the last N numbers
0547 template <typename T> class CMedianFilter
0548 {
0549 private:
0550     std::vector<T> vValues;
0551     std::vector<T> vSorted;
0552     int nSize;
0553 public:
0554     CMedianFilter(int size, T initial_value):
0555         nSize(size)
0556     {
0557         vValues.reserve(size);
0558         vValues.push_back(initial_value);
0559         vSorted = vValues;
0560     }
0561     
0562     void input(T value)
0563     {
0564         if(vValues.size() == nSize)
0565         {
0566             vValues.erase(vValues.begin());
0567         }
0568         vValues.push_back(value);
0569 
0570         vSorted.resize(vValues.size());
0571         std::copy(vValues.begin(), vValues.end(), vSorted.begin());
0572         std::sort(vSorted.begin(), vSorted.end());
0573     }
0574 
0575     T median() const
0576     {
0577         int size = vSorted.size();
0578         assert(size>0);
0579         if(size & 1) // Odd number of elements
0580         {
0581             return vSorted[size/2];
0582         }
0583         else // Even number of elements
0584         {
0585             return (vSorted[size/2-1] + vSorted[size/2]) / 2;
0586         }
0587     }
0588 };
0589 
0590 
0591 
0592 
0593 
0594 
0595 
0596 
0597 
0598 
0599 // Note: It turns out we might have been able to use boost::thread
0600 // by using TerminateThread(boost::thread.native_handle(), 0);
0601 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
0602 {
0603     pthread_t hthread = 0;
0604     int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
0605     if (ret != 0)
0606     {
0607         printf("Error: pthread_create() returned %d\n", ret);
0608         return (pthread_t)0;
0609     }
0610     if (!fWantHandle)
0611     {
0612         pthread_detach(hthread);
0613         return (pthread_t)-1;
0614     }
0615     return hthread;
0616 }
0617 
0618 #define THREAD_PRIORITY_LOWEST          PRIO_MAX
0619 #define THREAD_PRIORITY_BELOW_NORMAL    2
0620 #define THREAD_PRIORITY_NORMAL          0
0621 #define THREAD_PRIORITY_ABOVE_NORMAL    0
0622 
0623 inline void SetThreadPriority(int nPriority)
0624 {
0625     // It's unclear if it's even possible to change thread priorities on Linux,
0626     // but we really and truly need it for the generation threads.
0627 #ifdef PRIO_THREAD
0628     setpriority(PRIO_THREAD, 0, nPriority);
0629 #else
0630     setpriority(PRIO_PROCESS, 0, nPriority);
0631 #endif
0632 }
0633 
0634 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
0635 {
0636     return (pthread_cancel(hthread) == 0);
0637 }
0638 
0639 inline void ExitThread(size_t nExitCode)
0640 {
0641     pthread_exit((void*)nExitCode);
0642 }
0643 
0644 
0645 
0646 inline bool AffinityBugWorkaround(void(*pfn)(void*))
0647 {
0648     return false;
0649 }
0650 
0651 inline uint32_t ByteReverse(uint32_t value)
0652 {
0653     value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
0654     return (value<<16) | (value>>16);
0655 }
0656 
0657 #endif