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