Common.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /*
  2. This file is part of cpp-ethereum.
  3. cpp-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. cpp-ethereum is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /** @file Common.h
  15. * @author Gav Wood <i@gavwood.com>
  16. * @date 2014
  17. *
  18. * Very common stuff (i.e. that every other header needs except vector_ref.h).
  19. */
  20. #pragma once
  21. // way to many unsigned to size_t warnings in 32 bit build
  22. #ifdef _M_IX86
  23. #pragma warning(disable:4244)
  24. #endif
  25. #if _MSC_VER && _MSC_VER < 1900
  26. #define _ALLOW_KEYWORD_MACROS
  27. #define noexcept throw()
  28. #endif
  29. #ifdef __INTEL_COMPILER
  30. #pragma warning(disable:3682) //call through incomplete class
  31. #endif
  32. #include <map>
  33. #include <unordered_map>
  34. #include <vector>
  35. #include <set>
  36. #include <unordered_set>
  37. #include <functional>
  38. #include <string>
  39. #include <chrono>
  40. #pragma warning(push)
  41. #pragma GCC diagnostic push
  42. #pragma GCC diagnostic ignored "-Wunused-parameter"
  43. #include <boost/version.hpp>
  44. #if (BOOST_VERSION == 105800)
  45. #include "boost_multiprecision_number_compare_bug_workaround.hpp"
  46. #endif
  47. #include <boost/multiprecision/cpp_int.hpp>
  48. #pragma warning(pop)
  49. #pragma GCC diagnostic pop
  50. #include "vector_ref.h"
  51. // CryptoPP defines byte in the global namespace, so must we.
  52. using byte = uint8_t;
  53. // Quote a given token stream to turn it into a string.
  54. #define DEV_QUOTED_HELPER(s) #s
  55. #define DEV_QUOTED(s) DEV_QUOTED_HELPER(s)
  56. #define DEV_IGNORE_EXCEPTIONS(X) try { X; } catch (...) {}
  57. #define DEV_IF_NO_ELSE(X) if(!(X)){}else
  58. #define DEV_IF_THROWS(X) try{X;}catch(...)
  59. namespace dev
  60. {
  61. extern char const* Version;
  62. static const std::string EmptyString;
  63. // Binary data types.
  64. using bytes = std::vector<byte>;
  65. using bytesRef = vector_ref<byte>;
  66. using bytesConstRef = vector_ref<byte const>;
  67. template <class T>
  68. class secure_vector
  69. {
  70. public:
  71. secure_vector() {}
  72. secure_vector(secure_vector<T> const& /*_c*/) = default; // See https://github.com/ethereum/libweb3core/pull/44
  73. explicit secure_vector(unsigned _size): m_data(_size) {}
  74. explicit secure_vector(unsigned _size, T _item): m_data(_size, _item) {}
  75. explicit secure_vector(std::vector<T> const& _c): m_data(_c) {}
  76. explicit secure_vector(vector_ref<T> _c): m_data(_c.data(), _c.data() + _c.size()) {}
  77. explicit secure_vector(vector_ref<const T> _c): m_data(_c.data(), _c.data() + _c.size()) {}
  78. ~secure_vector() { ref().cleanse(); }
  79. secure_vector<T>& operator=(secure_vector<T> const& _c)
  80. {
  81. if (&_c == this)
  82. return *this;
  83. ref().cleanse();
  84. m_data = _c.m_data;
  85. return *this;
  86. }
  87. std::vector<T>& writable() { clear(); return m_data; }
  88. std::vector<T> const& makeInsecure() const { return m_data; }
  89. void clear() { ref().cleanse(); }
  90. vector_ref<T> ref() { return vector_ref<T>(&m_data); }
  91. vector_ref<T const> ref() const { return vector_ref<T const>(&m_data); }
  92. size_t size() const { return m_data.size(); }
  93. bool empty() const { return m_data.empty(); }
  94. void swap(secure_vector<T>& io_other) { m_data.swap(io_other.m_data); }
  95. private:
  96. std::vector<T> m_data;
  97. };
  98. using bytesSec = secure_vector<byte>;
  99. // Numeric types.
  100. using bigint = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<>>;
  101. using u64 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<64, 64, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>;
  102. using u128 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<128, 128, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>;
  103. using u256 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>;
  104. using s256 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<256, 256, boost::multiprecision::signed_magnitude, boost::multiprecision::unchecked, void>>;
  105. using u160 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<160, 160, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>;
  106. using s160 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<160, 160, boost::multiprecision::signed_magnitude, boost::multiprecision::unchecked, void>>;
  107. using u512 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<512, 512, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>;
  108. using s512 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<512, 512, boost::multiprecision::signed_magnitude, boost::multiprecision::unchecked, void>>;
  109. using u256s = std::vector<u256>;
  110. using u160s = std::vector<u160>;
  111. using u256Set = std::set<u256>;
  112. using u160Set = std::set<u160>;
  113. // Map types.
  114. using StringMap = std::map<std::string, std::string>;
  115. using BytesMap = std::map<bytes, bytes>;
  116. using u256Map = std::map<u256, u256>;
  117. using HexMap = std::map<bytes, bytes>;
  118. // Hash types.
  119. using StringHashMap = std::unordered_map<std::string, std::string>;
  120. using u256HashMap = std::unordered_map<u256, u256>;
  121. // String types.
  122. using strings = std::vector<std::string>;
  123. // Fixed-length string types.
  124. using string32 = std::array<char, 32>;
  125. static const string32 ZeroString32 = {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }};
  126. // Null/Invalid values for convenience.
  127. static const bytes NullBytes;
  128. static const std::map<u256, u256> EmptyMapU256U256;
  129. extern const u256 Invalid256;
  130. /// Interprets @a _u as a two's complement signed number and returns the resulting s256.
  131. inline s256 u2s(u256 _u)
  132. {
  133. static const bigint c_end = bigint(1) << 256;
  134. if (boost::multiprecision::bit_test(_u, 255))
  135. return s256(-(c_end - _u));
  136. else
  137. return s256(_u);
  138. }
  139. /// @returns the two's complement signed representation of the signed number _u.
  140. inline u256 s2u(s256 _u)
  141. {
  142. static const bigint c_end = bigint(1) << 256;
  143. if (_u >= 0)
  144. return u256(_u);
  145. else
  146. return u256(c_end + _u);
  147. }
  148. /// Converts given int to a string and appends one of a series of units according to its size.
  149. std::string inUnits(bigint const& _b, strings const& _units);
  150. /// @returns the smallest n >= 0 such that (1 << n) >= _x
  151. inline unsigned int toLog2(u256 _x)
  152. {
  153. unsigned ret;
  154. for (ret = 0; _x >>= 1; ++ret) {}
  155. return ret;
  156. }
  157. template <size_t n> inline u256 exp10()
  158. {
  159. return exp10<n - 1>() * u256(10);
  160. }
  161. template <> inline u256 exp10<0>()
  162. {
  163. return u256(1);
  164. }
  165. /// @returns the absolute distance between _a and _b.
  166. template <class N>
  167. inline N diff(N const& _a, N const& _b)
  168. {
  169. return std::max(_a, _b) - std::min(_a, _b);
  170. }
  171. /// RAII utility class whose destructor calls a given function.
  172. class ScopeGuard
  173. {
  174. public:
  175. ScopeGuard(std::function<void(void)> _f): m_f(_f) {}
  176. ~ScopeGuard() { m_f(); }
  177. private:
  178. std::function<void(void)> m_f;
  179. };
  180. /// Inheritable for classes that have invariants.
  181. class HasInvariants
  182. {
  183. public:
  184. /// Reimplement to specify the invariants.
  185. virtual bool invariants() const = 0;
  186. };
  187. /// RAII checker for invariant assertions.
  188. class InvariantChecker
  189. {
  190. public:
  191. InvariantChecker(HasInvariants* _this, char const* _fn, char const* _file, int _line): m_this(_this), m_function(_fn), m_file(_file), m_line(_line) { checkInvariants(_this, _fn , _file, _line, true); }
  192. ~InvariantChecker() { checkInvariants(m_this, m_function, m_file, m_line, false); }
  193. /// Check invariants are met, throw if not.
  194. static void checkInvariants(HasInvariants const* _this, char const* _fn, char const* _file, int line, bool _pre);
  195. private:
  196. HasInvariants const* m_this;
  197. char const* m_function;
  198. char const* m_file;
  199. int m_line;
  200. };
  201. /// Scope guard for invariant check in a class derived from HasInvariants.
  202. #if ETH_DEBUG
  203. #define DEV_INVARIANT_CHECK ::dev::InvariantChecker __dev_invariantCheck(this, BOOST_CURRENT_FUNCTION, __FILE__, __LINE__)
  204. #define DEV_INVARIANT_CHECK_HERE ::dev::InvariantChecker::checkInvariants(this, BOOST_CURRENT_FUNCTION, __FILE__, __LINE__, true)
  205. #else
  206. #define DEV_INVARIANT_CHECK (void)0;
  207. #define DEV_INVARIANT_CHECK_HERE (void)0;
  208. #endif
  209. /// Simple scope-based timer helper.
  210. class TimerHelper
  211. {
  212. public:
  213. TimerHelper(std::string const& _id, unsigned _msReportWhenGreater = 0): m_t(std::chrono::high_resolution_clock::now()), m_id(_id), m_ms(_msReportWhenGreater) {}
  214. ~TimerHelper();
  215. private:
  216. std::chrono::high_resolution_clock::time_point m_t;
  217. std::string m_id;
  218. unsigned m_ms;
  219. };
  220. class Timer
  221. {
  222. public:
  223. Timer() { restart(); }
  224. std::chrono::high_resolution_clock::duration duration() const { return std::chrono::high_resolution_clock::now() - m_t; }
  225. double elapsed() const { return std::chrono::duration_cast<std::chrono::microseconds>(duration()).count() / 1000000.0; }
  226. void restart() { m_t = std::chrono::high_resolution_clock::now(); }
  227. private:
  228. std::chrono::high_resolution_clock::time_point m_t;
  229. };
  230. #define DEV_TIMED(S) for (::std::pair<::dev::TimerHelper, bool> __eth_t(S, true); __eth_t.second; __eth_t.second = false)
  231. #define DEV_TIMED_SCOPE(S) ::dev::TimerHelper __eth_t(S)
  232. #if defined(_WIN32)
  233. #define DEV_TIMED_FUNCTION DEV_TIMED_SCOPE(__FUNCSIG__)
  234. #else
  235. #define DEV_TIMED_FUNCTION DEV_TIMED_SCOPE(__PRETTY_FUNCTION__)
  236. #endif
  237. #define DEV_TIMED_ABOVE(S, MS) for (::std::pair<::dev::TimerHelper, bool> __eth_t(::dev::TimerHelper(S, MS), true); __eth_t.second; __eth_t.second = false)
  238. #define DEV_TIMED_SCOPE_ABOVE(S, MS) ::dev::TimerHelper __eth_t(S, MS)
  239. #if defined(_WIN32)
  240. #define DEV_TIMED_FUNCTION_ABOVE(MS) DEV_TIMED_SCOPE_ABOVE(__FUNCSIG__, MS)
  241. #else
  242. #define DEV_TIMED_FUNCTION_ABOVE(MS) DEV_TIMED_SCOPE_ABOVE(__PRETTY_FUNCTION__, MS)
  243. #endif
  244. #ifdef _MSC_VER
  245. // TODO.
  246. #define DEV_UNUSED
  247. #else
  248. #define DEV_UNUSED __attribute__((unused))
  249. #endif
  250. enum class WithExisting: int
  251. {
  252. Trust = 0,
  253. Verify,
  254. Rescue,
  255. Kill
  256. };
  257. /// Get the current time in seconds since the epoch in UTC
  258. uint64_t utcTime();
  259. }
  260. namespace std
  261. {
  262. inline dev::WithExisting max(dev::WithExisting _a, dev::WithExisting _b)
  263. {
  264. return static_cast<dev::WithExisting>(max(static_cast<int>(_a), static_cast<int>(_b)));
  265. }
  266. template <> struct hash<dev::u256>
  267. {
  268. size_t operator()(dev::u256 const& _a) const
  269. {
  270. unsigned size = _a.backend().size();
  271. auto limbs = _a.backend().limbs();
  272. return boost::hash_range(limbs, limbs + size);
  273. }
  274. };
  275. }