BlockChain.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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 BlockChain.h
  15. * @author Gav Wood <i@gavwood.com>
  16. * @date 2014
  17. */
  18. #pragma once
  19. #include <deque>
  20. #include <chrono>
  21. #include <unordered_map>
  22. #include <unordered_set>
  23. #include <libdevcore/db.h>
  24. #include <libdevcore/Log.h>
  25. #include <libdevcore/Exceptions.h>
  26. #include <libdevcore/Guards.h>
  27. #include <libethcore/Common.h>
  28. #include <libethcore/BlockHeader.h>
  29. #include <libethcore/SealEngine.h>
  30. #include <libevm/ExtVMFace.h>
  31. #include "BlockDetails.h"
  32. #include "Account.h"
  33. #include "Transaction.h"
  34. #include "BlockQueue.h"
  35. #include "VerifiedBlock.h"
  36. #include "ChainParams.h"
  37. #include "State.h"
  38. namespace std
  39. {
  40. template <> struct hash<pair<dev::h256, unsigned>>
  41. {
  42. size_t operator()(pair<dev::h256, unsigned> const& _x) const { return hash<dev::h256>()(_x.first) ^ hash<unsigned>()(_x.second); }
  43. };
  44. }
  45. namespace dev
  46. {
  47. class OverlayDB;
  48. namespace eth
  49. {
  50. static const h256s NullH256s;
  51. class State;
  52. class Block;
  53. DEV_SIMPLE_EXCEPTION(AlreadyHaveBlock);
  54. DEV_SIMPLE_EXCEPTION(FutureTime);
  55. DEV_SIMPLE_EXCEPTION(TransientError);
  56. struct BlockChainChat: public LogChannel { static const char* name(); static const int verbosity = 5; };
  57. struct BlockChainNote: public LogChannel { static const char* name(); static const int verbosity = 3; };
  58. struct BlockChainWarn: public LogChannel { static const char* name(); static const int verbosity = 1; };
  59. struct BlockChainDebug: public LogChannel { static const char* name(); static const int verbosity = 0; };
  60. // TODO: Move all this Genesis stuff into Genesis.h/.cpp
  61. std::unordered_map<Address, Account> const& genesisState();
  62. ldb::Slice toSlice(h256 const& _h, unsigned _sub = 0);
  63. ldb::Slice toSlice(uint64_t _n, unsigned _sub = 0);
  64. using BlocksHash = std::unordered_map<h256, bytes>;
  65. using TransactionHashes = h256s;
  66. using UncleHashes = h256s;
  67. enum {
  68. ExtraDetails = 0,
  69. ExtraBlockHash,
  70. ExtraTransactionAddress,
  71. ExtraLogBlooms,
  72. ExtraReceipts,
  73. ExtraBlocksBlooms
  74. };
  75. using ProgressCallback = std::function<void(unsigned, unsigned)>;
  76. class VersionChecker
  77. {
  78. public:
  79. VersionChecker(std::string const& _dbPath, h256 const& _genesisHash);
  80. };
  81. /**
  82. * @brief Implements the blockchain database. All data this gives is disk-backed.
  83. * @threadsafe
  84. */
  85. class BlockChain
  86. {
  87. public:
  88. /// Doesn't open the database - if you want it open it's up to you to subclass this and open it
  89. /// in the constructor there.
  90. BlockChain(ChainParams const& _p, std::string const& _path, WithExisting _we = WithExisting::Trust, ProgressCallback const& _pc = ProgressCallback());
  91. ~BlockChain();
  92. /// Reopen everything.
  93. void reopen(WithExisting _we = WithExisting::Trust, ProgressCallback const& _pc = ProgressCallback()) { reopen(m_params, _we, _pc); }
  94. void reopen(ChainParams const& _p, WithExisting _we = WithExisting::Trust, ProgressCallback const& _pc = ProgressCallback());
  95. /// (Potentially) renders invalid existing bytesConstRef returned by lastBlock.
  96. /// To be called from main loop every 100ms or so.
  97. void process();
  98. /// Sync the chain with any incoming blocks. All blocks should, if processed in order.
  99. /// @returns fresh blocks, dead blocks and true iff there are additional blocks to be processed waiting.
  100. std::tuple<ImportRoute, bool, unsigned> sync(BlockQueue& _bq, OverlayDB const& _stateDB, unsigned _max);
  101. /// Attempt to import the given block directly into the BlockChain and sync with the state DB.
  102. /// @returns the block hashes of any blocks that came into/went out of the canonical block chain.
  103. std::pair<ImportResult, ImportRoute> attemptImport(bytes const& _block, OverlayDB const& _stateDB, bool _mutBeNew = true) noexcept;
  104. /// Import block into disk-backed DB.
  105. /// @returns the block hashes of any blocks that came into/went out of the canonical block chain.
  106. ImportRoute import(bytes const& _block, OverlayDB const& _stateDB, bool _mustBeNew = true);
  107. ImportRoute import(VerifiedBlockRef const& _block, OverlayDB const& _db, bool _mustBeNew = true);
  108. /// Import data into disk-backed DB.
  109. /// This will not execute the block and populate the state trie, but rather will simply add the
  110. /// block/header and receipts directly into the databases.
  111. void insert(bytes const& _block, bytesConstRef _receipts, bool _mustBeNew = true);
  112. void insert(VerifiedBlockRef _block, bytesConstRef _receipts, bool _mustBeNew = true);
  113. /// Returns true if the given block is known (though not necessarily a part of the canon chain).
  114. bool isKnown(h256 const& _hash, bool _isCurrent = true) const;
  115. /// Get the partial-header of a block (or the most recent mined if none given). Thread-safe.
  116. BlockHeader info(h256 const& _hash) const { return BlockHeader(headerData(_hash), HeaderData); }
  117. BlockHeader info() const { return info(currentHash()); }
  118. /// Get a block (RLP format) for the given hash (or the most recent mined if none given). Thread-safe.
  119. bytes block(h256 const& _hash) const;
  120. bytes block() const { return block(currentHash()); }
  121. /// Get a block (RLP format) for the given hash (or the most recent mined if none given). Thread-safe.
  122. bytes headerData(h256 const& _hash) const;
  123. bytes headerData() const { return headerData(currentHash()); }
  124. /// Get the familial details concerning a block (or the most recent mined if none given). Thread-safe.
  125. BlockDetails details(h256 const& _hash) const { return queryExtras<BlockDetails, ExtraDetails>(_hash, m_details, x_details, NullBlockDetails); }
  126. BlockDetails details() const { return details(currentHash()); }
  127. /// Get the transactions' log blooms of a block (or the most recent mined if none given). Thread-safe.
  128. BlockLogBlooms logBlooms(h256 const& _hash) const { return queryExtras<BlockLogBlooms, ExtraLogBlooms>(_hash, m_logBlooms, x_logBlooms, NullBlockLogBlooms); }
  129. BlockLogBlooms logBlooms() const { return logBlooms(currentHash()); }
  130. /// Get the transactions' receipts of a block (or the most recent mined if none given). Thread-safe.
  131. /// receipts are given in the same order are in the same order as the transactions
  132. BlockReceipts receipts(h256 const& _hash) const { return queryExtras<BlockReceipts, ExtraReceipts>(_hash, m_receipts, x_receipts, NullBlockReceipts); }
  133. BlockReceipts receipts() const { return receipts(currentHash()); }
  134. /// Get the transaction by block hash and index;
  135. TransactionReceipt transactionReceipt(h256 const& _blockHash, unsigned _i) const { return receipts(_blockHash).receipts[_i]; }
  136. /// Get the transaction receipt by transaction hash. Thread-safe.
  137. TransactionReceipt transactionReceipt(h256 const& _transactionHash) const { TransactionAddress ta = queryExtras<TransactionAddress, ExtraTransactionAddress>(_transactionHash, m_transactionAddresses, x_transactionAddresses, NullTransactionAddress); if (!ta) return bytesConstRef(); return transactionReceipt(ta.blockHash, ta.index); }
  138. /// Get a list of transaction hashes for a given block. Thread-safe.
  139. TransactionHashes transactionHashes(h256 const& _hash) const { auto b = block(_hash); RLP rlp(b); h256s ret; for (auto t: rlp[1]) ret.push_back(sha3(t.data())); return ret; }
  140. TransactionHashes transactionHashes() const { return transactionHashes(currentHash()); }
  141. /// Get a list of uncle hashes for a given block. Thread-safe.
  142. UncleHashes uncleHashes(h256 const& _hash) const { auto b = block(_hash); RLP rlp(b); h256s ret; for (auto t: rlp[2]) ret.push_back(sha3(t.data())); return ret; }
  143. UncleHashes uncleHashes() const { return uncleHashes(currentHash()); }
  144. /// Get the hash for a given block's number.
  145. h256 numberHash(unsigned _i) const { if (!_i) return genesisHash(); return queryExtras<BlockHash, uint64_t, ExtraBlockHash>(_i, m_blockHashes, x_blockHashes, NullBlockHash).value; }
  146. /// Get the last N hashes for a given block. (N is determined by the LastHashes type.)
  147. LastHashes lastHashes() const { return lastHashes(m_lastBlockHash); }
  148. LastHashes lastHashes(h256 const& _mostRecentHash) const;
  149. /** Get the block blooms for a number of blocks. Thread-safe.
  150. * @returns the object pertaining to the blocks:
  151. * level 0:
  152. * 0x, 0x + 1, .. (1x - 1)
  153. * 1x, 1x + 1, .. (2x - 1)
  154. * ...
  155. * (255x .. (256x - 1))
  156. * level 1:
  157. * 0x .. (1x - 1), 1x .. (2x - 1), ..., (255x .. (256x - 1))
  158. * 256x .. (257x - 1), 257x .. (258x - 1), ..., (511x .. (512x - 1))
  159. * ...
  160. * level n, index i, offset o:
  161. * i * (x ^ n) + o * x ^ (n - 1)
  162. */
  163. BlocksBlooms blocksBlooms(unsigned _level, unsigned _index) const { return blocksBlooms(chunkId(_level, _index)); }
  164. BlocksBlooms blocksBlooms(h256 const& _chunkId) const { return queryExtras<BlocksBlooms, ExtraBlocksBlooms>(_chunkId, m_blocksBlooms, x_blocksBlooms, NullBlocksBlooms); }
  165. LogBloom blockBloom(unsigned _number) const { return blocksBlooms(chunkId(0, _number / c_bloomIndexSize)).blooms[_number % c_bloomIndexSize]; }
  166. std::vector<unsigned> withBlockBloom(LogBloom const& _b, unsigned _earliest, unsigned _latest) const;
  167. std::vector<unsigned> withBlockBloom(LogBloom const& _b, unsigned _earliest, unsigned _latest, unsigned _topLevel, unsigned _index) const;
  168. /// Returns true if transaction is known. Thread-safe
  169. bool isKnownTransaction(h256 const& _transactionHash) const { TransactionAddress ta = queryExtras<TransactionAddress, ExtraTransactionAddress>(_transactionHash, m_transactionAddresses, x_transactionAddresses, NullTransactionAddress); return !!ta; }
  170. /// Get a transaction from its hash. Thread-safe.
  171. bytes transaction(h256 const& _transactionHash) const { TransactionAddress ta = queryExtras<TransactionAddress, ExtraTransactionAddress>(_transactionHash, m_transactionAddresses, x_transactionAddresses, NullTransactionAddress); if (!ta) return bytes(); return transaction(ta.blockHash, ta.index); }
  172. std::pair<h256, unsigned> transactionLocation(h256 const& _transactionHash) const { TransactionAddress ta = queryExtras<TransactionAddress, ExtraTransactionAddress>(_transactionHash, m_transactionAddresses, x_transactionAddresses, NullTransactionAddress); if (!ta) return std::pair<h256, unsigned>(h256(), 0); return std::make_pair(ta.blockHash, ta.index); }
  173. /// Get a block's transaction (RLP format) for the given block hash (or the most recent mined if none given) & index. Thread-safe.
  174. bytes transaction(h256 const& _blockHash, unsigned _i) const { bytes b = block(_blockHash); return RLP(b)[1][_i].data().toBytes(); }
  175. bytes transaction(unsigned _i) const { return transaction(currentHash(), _i); }
  176. /// Get all transactions from a block.
  177. std::vector<bytes> transactions(h256 const& _blockHash) const { bytes b = block(_blockHash); std::vector<bytes> ret; for (auto const& i: RLP(b)[1]) ret.push_back(i.data().toBytes()); return ret; }
  178. std::vector<bytes> transactions() const { return transactions(currentHash()); }
  179. /// Get a number for the given hash (or the most recent mined if none given). Thread-safe.
  180. unsigned number(h256 const& _hash) const { return details(_hash).number; }
  181. unsigned number() const { return m_lastBlockNumber; }
  182. /// Get a given block (RLP format). Thread-safe.
  183. h256 currentHash() const { ReadGuard l(x_lastBlockHash); return m_lastBlockHash; }
  184. /// Get the hash of the genesis block. Thread-safe.
  185. h256 genesisHash() const { return m_genesisHash; }
  186. /// Get all blocks not allowed as uncles given a parent (i.e. featured as uncles/main in parent, parent + 1, ... parent + @a _generations).
  187. /// @returns set including the header-hash of every parent (including @a _parent) up to and including generation + @a _generations
  188. /// togther with all their quoted uncles.
  189. h256Hash allKinFrom(h256 const& _parent, unsigned _generations) const;
  190. /// Run through database and verify all blocks by reevaluating.
  191. /// Will call _progress with the progress in this operation first param done, second total.
  192. void rebuild(std::string const& _path, ProgressCallback const& _progress = std::function<void(unsigned, unsigned)>());
  193. /// Alter the head of the chain to some prior block along it.
  194. void rewind(unsigned _newHead);
  195. /// Rescue the database.
  196. void rescue(OverlayDB const& _db);
  197. /** @returns a tuple of:
  198. * - an vector of hashes of all blocks between @a _from and @a _to, all blocks are ordered first by a number of
  199. * blocks that are parent-to-child, then two sibling blocks, then a number of blocks that are child-to-parent;
  200. * - the block hash of the latest common ancestor of both blocks;
  201. * - the index where the latest common ancestor of both blocks would either be found or inserted, depending
  202. * on whether it is included.
  203. *
  204. * @param _common if true, include the common ancestor in the returned vector.
  205. * @param _pre if true, include all block hashes running from @a _from until the common ancestor in the returned vector.
  206. * @param _post if true, include all block hashes running from the common ancestor until @a _to in the returned vector.
  207. *
  208. * e.g. if the block tree is 3a -> 2a -> 1a -> g and 2b -> 1b -> g (g is genesis, *a, *b are competing chains),
  209. * then:
  210. * @code
  211. * treeRoute(3a, 2b, false) == make_tuple({ 3a, 2a, 1a, 1b, 2b }, g, 3);
  212. * treeRoute(2a, 1a, false) == make_tuple({ 2a, 1a }, 1a, 1)
  213. * treeRoute(1a, 2a, false) == make_tuple({ 1a, 2a }, 1a, 0)
  214. * treeRoute(1b, 2a, false) == make_tuple({ 1b, 1a, 2a }, g, 1)
  215. * treeRoute(3a, 2b, true) == make_tuple({ 3a, 2a, 1a, g, 1b, 2b }, g, 3);
  216. * treeRoute(2a, 1a, true) == make_tuple({ 2a, 1a }, 1a, 1)
  217. * treeRoute(1a, 2a, true) == make_tuple({ 1a, 2a }, 1a, 0)
  218. * treeRoute(1b, 2a, true) == make_tuple({ 1b, g, 1a, 2a }, g, 1)
  219. * @endcode
  220. */
  221. std::tuple<h256s, h256, unsigned> treeRoute(h256 const& _from, h256 const& _to, bool _common = true, bool _pre = true, bool _post = true) const;
  222. struct Statistics
  223. {
  224. unsigned memBlocks;
  225. unsigned memDetails;
  226. unsigned memLogBlooms;
  227. unsigned memReceipts;
  228. unsigned memTransactionAddresses;
  229. unsigned memBlockHashes;
  230. unsigned memTotal() const { return memBlocks + memDetails + memLogBlooms + memReceipts + memTransactionAddresses + memBlockHashes; }
  231. };
  232. /// @returns statistics about memory usage.
  233. Statistics usage(bool _freshen = false) const { if (_freshen) updateStats(); return m_lastStats; }
  234. /// Deallocate unused data.
  235. void garbageCollect(bool _force = false);
  236. /// Change the function that is called with a bad block.
  237. template <class T> void setOnBad(T const& _t) { m_onBad = _t; }
  238. /// Get a pre-made genesis State object.
  239. Block genesisBlock(OverlayDB const& _db) const;
  240. /// Verify block and prepare it for enactment
  241. VerifiedBlockRef verifyBlock(bytesConstRef _block, std::function<void(Exception&)> const& _onBad, ImportRequirements::value _ir = ImportRequirements::OutOfOrderChecks) const;
  242. /// Gives a dump of the blockchain database. For debug/test use only.
  243. std::string dumpDatabase() const;
  244. ChainParams const& chainParams() const { return m_params; }
  245. SealEngineFace* sealEngine() const { return m_sealEngine.get(); }
  246. BlockHeader const& genesis() const;
  247. private:
  248. static h256 chunkId(unsigned _level, unsigned _index) { return h256(_index * 0xff + _level); }
  249. /// Initialise everything and ready for openning the database.
  250. // TODO: rename to init
  251. void init(ChainParams const& _p, std::string const& _path);
  252. /// Open the database.
  253. // TODO: rename to open.
  254. unsigned open(std::string const& _path, WithExisting _we);
  255. /// Open the database, rebuilding if necessary.
  256. void open(std::string const& _path, WithExisting _we, ProgressCallback const& _pc);
  257. /// Finalise everything and close the database.
  258. void close();
  259. template<class T, class K, unsigned N> T queryExtras(K const& _h, std::unordered_map<K, T>& _m, boost::shared_mutex& _x, T const& _n, ldb::DB* _extrasDB = nullptr) const
  260. {
  261. {
  262. ReadGuard l(_x);
  263. auto it = _m.find(_h);
  264. if (it != _m.end())
  265. return it->second;
  266. }
  267. std::string s;
  268. (_extrasDB ? _extrasDB : m_extrasDB)->Get(m_readOptions, toSlice(_h, N), &s);
  269. if (s.empty())
  270. return _n;
  271. noteUsed(_h, N);
  272. WriteGuard l(_x);
  273. auto ret = _m.insert(std::make_pair(_h, T(RLP(s))));
  274. return ret.first->second;
  275. }
  276. template<class T, unsigned N> T queryExtras(h256 const& _h, std::unordered_map<h256, T>& _m, boost::shared_mutex& _x, T const& _n, ldb::DB* _extrasDB = nullptr) const
  277. {
  278. return queryExtras<T, h256, N>(_h, _m, _x, _n, _extrasDB);
  279. }
  280. void checkConsistency();
  281. /// Clears all caches from the tip of the chain up to (including) _firstInvalid.
  282. /// These include the blooms, the block hashes and the transaction lookup tables.
  283. void clearCachesDuringChainReversion(unsigned _firstInvalid);
  284. void clearBlockBlooms(unsigned _begin, unsigned _end);
  285. /// The caches of the disk DB and their locks.
  286. mutable SharedMutex x_blocks;
  287. mutable BlocksHash m_blocks;
  288. mutable SharedMutex x_details;
  289. mutable BlockDetailsHash m_details;
  290. mutable SharedMutex x_logBlooms;
  291. mutable BlockLogBloomsHash m_logBlooms;
  292. mutable SharedMutex x_receipts;
  293. mutable BlockReceiptsHash m_receipts;
  294. mutable SharedMutex x_transactionAddresses;
  295. mutable TransactionAddressHash m_transactionAddresses;
  296. mutable SharedMutex x_blockHashes;
  297. mutable BlockHashHash m_blockHashes;
  298. mutable SharedMutex x_blocksBlooms;
  299. mutable BlocksBloomsHash m_blocksBlooms;
  300. using CacheID = std::pair<h256, unsigned>;
  301. mutable Mutex x_cacheUsage;
  302. mutable std::deque<std::unordered_set<CacheID>> m_cacheUsage;
  303. mutable std::unordered_set<CacheID> m_inUse;
  304. void noteUsed(h256 const& _h, unsigned _extra = (unsigned)-1) const;
  305. void noteUsed(uint64_t const& _h, unsigned _extra = (unsigned)-1) const { (void)_h; (void)_extra; } // don't note non-hash types
  306. std::chrono::system_clock::time_point m_lastCollection;
  307. void noteCanonChanged() const { Guard l(x_lastLastHashes); m_lastLastHashes.clear(); }
  308. mutable Mutex x_lastLastHashes;
  309. mutable LastHashes m_lastLastHashes;
  310. void updateStats() const;
  311. mutable Statistics m_lastStats;
  312. /// The disk DBs. Thread-safe, so no need for locks.
  313. ldb::DB* m_blocksDB;
  314. ldb::DB* m_extrasDB;
  315. /// Hash of the last (valid) block on the longest chain.
  316. mutable boost::shared_mutex x_lastBlockHash;
  317. h256 m_lastBlockHash;
  318. unsigned m_lastBlockNumber = 0;
  319. ldb::ReadOptions m_readOptions;
  320. ldb::WriteOptions m_writeOptions;
  321. ChainParams m_params;
  322. std::shared_ptr<SealEngineFace> m_sealEngine; // consider shared_ptr.
  323. mutable SharedMutex x_genesis;
  324. mutable BlockHeader m_genesis; // mutable because they're effectively memos.
  325. mutable bytes m_genesisHeaderBytes; // mutable because they're effectively memos.
  326. mutable h256 m_genesisHash; // mutable because they're effectively memos.
  327. std::function<void(Exception&)> m_onBad; ///< Called if we have a block that doesn't verify.
  328. std::string m_dbPath;
  329. friend std::ostream& operator<<(std::ostream& _out, BlockChain const& _bc);
  330. };
  331. std::ostream& operator<<(std::ostream& _out, BlockChain const& _bc);
  332. }
  333. }