Back to home page

Bitcoin sources

 
 

    


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 
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 char pszSetDataDir[MAX_PATH];
0114 extern bool fRequestShutdown;
0115 extern bool fShutdown;
0116 extern bool fDaemon;
0117 extern bool fServer;
0118 extern bool fCommandLine;
0119 extern std::string strMiscWarning;
0120 extern bool fTestNet;
0121 extern bool fNoListen;
0122 extern bool fLogTimestamps;
0123 
0124 void RandAddSeed();
0125 void RandAddSeedPerfmon();
0126 int OutputDebugStringF(const char* pszFormat, ...);
0127 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
0128 std::string strprintf(const std::string &format, ...);
0129 bool error(const std::string &format, ...);
0130 void LogException(std::exception* pex, const char* pszThread);
0131 void PrintException(std::exception* pex, const char* pszThread);
0132 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
0133 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
0134 std::string FormatMoney(int64 n, bool fPlus=false);
0135 bool ParseMoney(const std::string& str, int64& nRet);
0136 bool ParseMoney(const char* pszIn, int64& nRet);
0137 std::vector<unsigned char> ParseHex(const char* psz);
0138 std::vector<unsigned char> ParseHex(const std::string& str);
0139 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
0140 std::string DecodeBase64(const std::string& str);
0141 std::string EncodeBase64(const unsigned char* pch, size_t len);
0142 std::string EncodeBase64(const std::string& str);
0143 void ParseParameters(int argc, char* argv[]);
0144 const char* wxGetTranslation(const char* psz);
0145 bool WildcardMatch(const char* psz, const char* mask);
0146 bool WildcardMatch(const std::string& str, const std::string& mask);
0147 int GetFilesize(FILE* file);
0148 void GetDataDir(char* pszDirRet);
0149 std::string GetConfigFile();
0150 std::string GetPidFile();
0151 void CreatePidFile(std::string pidFile, pid_t pid);
0152 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
0153 std::string GetDefaultDataDir();
0154 std::string GetDataDir();
0155 void ShrinkDebugFile();
0156 int GetRandInt(int nMax);
0157 uint64 GetRand(uint64 nMax);
0158 int64 GetTime();
0159 void SetMockTime(int64 nMockTimeIn);
0160 int64 GetAdjustedTime();
0161 void AddTimeData(unsigned int ip, int64 nTime);
0162 std::string FormatFullVersion();
0163 
0164 
0165 
0166 
0167 
0168 
0169 
0170 
0171 
0172 
0173 
0174 
0175 
0176 // Wrapper to automatically initialize mutex
0177 class CCriticalSection
0178 {
0179 protected:
0180     boost::interprocess::interprocess_recursive_mutex mutex;
0181 public:
0182     explicit CCriticalSection() { }
0183     ~CCriticalSection() { }
0184     void Enter(const char* pszName, const char* pszFile, int nLine);
0185     void Leave();
0186     bool TryEnter(const char* pszName, const char* pszFile, int nLine);
0187 };
0188 
0189 // Automatically leave critical section when leaving block, needed for exception safety
0190 class CCriticalBlock
0191 {
0192 protected:
0193     CCriticalSection* pcs;
0194 
0195 public:
0196     CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
0197     {
0198         pcs = &csIn;
0199         pcs->Enter(pszName, pszFile, nLine);
0200     }
0201 
0202     operator bool() const
0203     {
0204         return true;
0205     }
0206 
0207     ~CCriticalBlock()
0208     {
0209         pcs->Leave();
0210     }
0211 };
0212 
0213 #define CRITICAL_BLOCK(cs)     \
0214     if (CCriticalBlock criticalblock = CCriticalBlock(cs, #cs, __FILE__, __LINE__))
0215 
0216 #define ENTER_CRITICAL_SECTION(cs) \
0217     (cs).Enter(#cs, __FILE__, __LINE__)
0218 
0219 #define LEAVE_CRITICAL_SECTION(cs) \
0220     (cs).Leave()
0221 
0222 class CTryCriticalBlock
0223 {
0224 protected:
0225     CCriticalSection* pcs;
0226 
0227 public:
0228     CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
0229     {
0230         pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
0231     }
0232 
0233     operator bool() const
0234     {
0235         return Entered();
0236     }
0237 
0238     ~CTryCriticalBlock()
0239     {
0240         if (pcs)
0241         {
0242             pcs->Leave();
0243         }
0244     }
0245     bool Entered() const { return pcs != NULL; }
0246 };
0247 
0248 #define TRY_CRITICAL_BLOCK(cs)     \
0249     if (CTryCriticalBlock criticalblock = CTryCriticalBlock(cs, #cs, __FILE__, __LINE__))
0250 
0251 
0252 
0253 
0254 
0255 
0256 // This is exactly like std::string, but with a custom allocator.
0257 // (secure_allocator<> is defined in serialize.h)
0258 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
0259 
0260 // This is exactly like std::string, but with a custom allocator.
0261 // (secure_allocator<> is defined in serialize.h)
0262 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
0263 
0264 
0265 
0266 
0267 
0268 inline std::string i64tostr(int64 n)
0269 {
0270     return strprintf("%"PRI64d, n);
0271 }
0272 
0273 inline std::string itostr(int n)
0274 {
0275     return strprintf("%d", n);
0276 }
0277 
0278 inline int64 atoi64(const char* psz)
0279 {
0280     return strtoll(psz, NULL, 10);
0281 }
0282 
0283 inline int64 atoi64(const std::string& str)
0284 {
0285     return strtoll(str.c_str(), NULL, 10);
0286 }
0287 
0288 inline int atoi(const std::string& str)
0289 {
0290     return atoi(str.c_str());
0291 }
0292 
0293 inline int roundint(double d)
0294 {
0295     return (int)(d > 0 ? d + 0.5 : d - 0.5);
0296 }
0297 
0298 inline int64 roundint64(double d)
0299 {
0300     return (int64)(d > 0 ? d + 0.5 : d - 0.5);
0301 }
0302 
0303 inline int64 abs64(int64 n)
0304 {
0305     return (n >= 0 ? n : -n);
0306 }
0307 
0308 template<typename T>
0309 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
0310 {
0311     if (itbegin == itend)
0312         return "";
0313     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
0314     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
0315     std::string str;
0316     str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
0317     for (const unsigned char* p = pbegin; p != pend; p++)
0318         str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
0319     return str;
0320 }
0321 
0322 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
0323 {
0324     return HexStr(vch.begin(), vch.end(), fSpaces);
0325 }
0326 
0327 template<typename T>
0328 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
0329 {
0330     if (itbegin == itend)
0331         return "";
0332     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
0333     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
0334     std::string str = (f0x ? "0x" : "");
0335     str.reserve(str.size() + (pend-pbegin) * 2);
0336     for (const unsigned char* p = pend-1; p >= pbegin; p--)
0337         str += strprintf("%02x", *p);
0338     return str;
0339 }
0340 
0341 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
0342 {
0343     return HexNumStr(vch.begin(), vch.end(), f0x);
0344 }
0345 
0346 template<typename T>
0347 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
0348 {
0349     printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
0350 }
0351 
0352 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
0353 {
0354     printf(pszFormat, HexStr(vch, fSpaces).c_str());
0355 }
0356 
0357 inline int64 GetPerformanceCounter()
0358 {
0359     int64 nCounter = 0;
0360     timeval t;
0361     gettimeofday(&t, NULL);
0362     nCounter = t.tv_sec * 1000000 + t.tv_usec;
0363     return nCounter;
0364 }
0365 
0366 inline int64 GetTimeMillis()
0367 {
0368     return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
0369             boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
0370 }
0371 
0372 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
0373 {
0374     time_t n = nTime;
0375     struct tm* ptmTime = gmtime(&n);
0376     char pszTime[200];
0377     strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
0378     return pszTime;
0379 }
0380 
0381 template<typename T>
0382 void skipspaces(T& it)
0383 {
0384     while (isspace(*it))
0385         ++it;
0386 }
0387 
0388 inline bool IsSwitchChar(char c)
0389 {
0390     return c == '-';
0391 }
0392 
0393 inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
0394 {
0395     if (mapArgs.count(strArg))
0396         return mapArgs[strArg];
0397     return strDefault;
0398 }
0399 
0400 inline int64 GetArg(const std::string& strArg, int64 nDefault)
0401 {
0402     if (mapArgs.count(strArg))
0403         return atoi64(mapArgs[strArg]);
0404     return nDefault;
0405 }
0406 
0407 inline bool GetBoolArg(const std::string& strArg, bool fDefault=false)
0408 {
0409     if (mapArgs.count(strArg))
0410     {
0411         if (mapArgs[strArg].empty())
0412             return true;
0413         return (atoi(mapArgs[strArg]) != 0);
0414     }
0415     return fDefault;
0416 }
0417 
0418 /**
0419  * Set an argument if it doesn't already have a value
0420  *
0421  * @param strArg Argument to set (e.g. "-foo")
0422  * @param strValue Value (e.g. "1")
0423  * @return true if argument gets set, false if it already had a value
0424  */
0425 bool SoftSetArg(const std::string& strArg, const std::string& strValue);
0426 
0427 /**
0428  * Set a boolean argument if it doesn't already have a value
0429  *
0430  * @param strArg Argument to set (e.g. "-foo")
0431  * @param fValue Value (e.g. false)
0432  * @return true if argument gets set, false if it already had a value
0433  */
0434 bool SoftSetArg(const std::string& strArg, bool fValue);
0435 
0436 
0437 
0438 
0439 
0440 
0441 
0442 
0443 
0444 inline void heapchk()
0445 {
0446 }
0447 
0448 // Randomize the stack to help protect against buffer overrun exploits
0449 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn)     \
0450     {                                           \
0451         static char nLoops;                     \
0452         if (nLoops <= 0)                        \
0453             nLoops = GetRand(20) + 1;           \
0454         if (nLoops-- > 1)                       \
0455         {                                       \
0456             ThreadFn;                           \
0457             return;                             \
0458         }                                       \
0459     }
0460 
0461 #define CATCH_PRINT_EXCEPTION(pszFn)     \
0462     catch (std::exception& e) {          \
0463         PrintException(&e, (pszFn));     \
0464     } catch (...) {                      \
0465         PrintException(NULL, (pszFn));   \
0466     }
0467 
0468 
0469 
0470 
0471 
0472 
0473 
0474 
0475 
0476 
0477 template<typename T1>
0478 inline uint256 Hash(const T1 pbegin, const T1 pend)
0479 {
0480     static unsigned char pblank[1];
0481     uint256 hash1;
0482     SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
0483     uint256 hash2;
0484     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
0485     return hash2;
0486 }
0487 
0488 template<typename T1, typename T2>
0489 inline uint256 Hash(const T1 p1begin, const T1 p1end,
0490                     const T2 p2begin, const T2 p2end)
0491 {
0492     static unsigned char pblank[1];
0493     uint256 hash1;
0494     SHA256_CTX ctx;
0495     SHA256_Init(&ctx);
0496     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
0497     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
0498     SHA256_Final((unsigned char*)&hash1, &ctx);
0499     uint256 hash2;
0500     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
0501     return hash2;
0502 }
0503 
0504 template<typename T1, typename T2, typename T3>
0505 inline uint256 Hash(const T1 p1begin, const T1 p1end,
0506                     const T2 p2begin, const T2 p2end,
0507                     const T3 p3begin, const T3 p3end)
0508 {
0509     static unsigned char pblank[1];
0510     uint256 hash1;
0511     SHA256_CTX ctx;
0512     SHA256_Init(&ctx);
0513     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
0514     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
0515     SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
0516     SHA256_Final((unsigned char*)&hash1, &ctx);
0517     uint256 hash2;
0518     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
0519     return hash2;
0520 }
0521 
0522 template<typename T>
0523 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
0524 {
0525     // Most of the time is spent allocating and deallocating CDataStream's
0526     // buffer.  If this ever needs to be optimized further, make a CStaticStream
0527     // class with its buffer on the stack.
0528     CDataStream ss(nType, nVersion);
0529     ss.reserve(10000);
0530     ss << obj;
0531     return Hash(ss.begin(), ss.end());
0532 }
0533 
0534 inline uint160 Hash160(const std::vector<unsigned char>& vch)
0535 {
0536     uint256 hash1;
0537     SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
0538     uint160 hash2;
0539     RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
0540     return hash2;
0541 }
0542 
0543 
0544 // Median filter over a stream of values
0545 // Returns the median of the last N numbers
0546 template <typename T> class CMedianFilter
0547 {
0548 private:
0549     std::vector<T> vValues;
0550     std::vector<T> vSorted;
0551     int nSize;
0552 public:
0553     CMedianFilter(int size, T initial_value):
0554         nSize(size)
0555     {
0556         vValues.reserve(size);
0557         vValues.push_back(initial_value);
0558         vSorted = vValues;
0559     }
0560     
0561     void input(T value)
0562     {
0563         if(vValues.size() == nSize)
0564         {
0565             vValues.erase(vValues.begin());
0566         }
0567         vValues.push_back(value);
0568 
0569         vSorted.resize(vValues.size());
0570         std::copy(vValues.begin(), vValues.end(), vSorted.begin());
0571         std::sort(vSorted.begin(), vSorted.end());
0572     }
0573 
0574     T median() const
0575     {
0576         int size = vSorted.size();
0577         assert(size>0);
0578         if(size & 1) // Odd number of elements
0579         {
0580             return vSorted[size/2];
0581         }
0582         else // Even number of elements
0583         {
0584             return (vSorted[size/2-1] + vSorted[size/2]) / 2;
0585         }
0586     }
0587 };
0588 
0589 
0590 
0591 
0592 
0593 
0594 
0595 
0596 
0597 
0598 // Note: It turns out we might have been able to use boost::thread
0599 // by using TerminateThread(boost::thread.native_handle(), 0);
0600 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
0601 {
0602     pthread_t hthread = 0;
0603     int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
0604     if (ret != 0)
0605     {
0606         printf("Error: pthread_create() returned %d\n", ret);
0607         return (pthread_t)0;
0608     }
0609     if (!fWantHandle)
0610     {
0611         pthread_detach(hthread);
0612         return (pthread_t)-1;
0613     }
0614     return hthread;
0615 }
0616 
0617 #define THREAD_PRIORITY_LOWEST          PRIO_MAX
0618 #define THREAD_PRIORITY_BELOW_NORMAL    2
0619 #define THREAD_PRIORITY_NORMAL          0
0620 #define THREAD_PRIORITY_ABOVE_NORMAL    0
0621 
0622 inline void SetThreadPriority(int nPriority)
0623 {
0624     // It's unclear if it's even possible to change thread priorities on Linux,
0625     // but we really and truly need it for the generation threads.
0626 #ifdef PRIO_THREAD
0627     setpriority(PRIO_THREAD, 0, nPriority);
0628 #else
0629     setpriority(PRIO_PROCESS, 0, nPriority);
0630 #endif
0631 }
0632 
0633 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
0634 {
0635     return (pthread_cancel(hthread) == 0);
0636 }
0637 
0638 inline void ExitThread(size_t nExitCode)
0639 {
0640     pthread_exit((void*)nExitCode);
0641 }
0642 
0643 
0644 
0645 inline bool AffinityBugWorkaround(void(*pfn)(void*))
0646 {
0647     return false;
0648 }
0649 
0650 inline uint32_t ByteReverse(uint32_t value)
0651 {
0652     value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
0653     return (value<<16) | (value>>16);
0654 }
0655 
0656 #endif