BlockChainSync.h 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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 BlockChainSync.h
  15. * @author Gav Wood <i@gavwood.com>
  16. * @date 2014
  17. */
  18. #pragma once
  19. #include <mutex>
  20. #include <unordered_map>
  21. #include <libdevcore/Guards.h>
  22. #include <libethcore/Common.h>
  23. #include <libp2p/Common.h>
  24. #include "CommonNet.h"
  25. namespace dev
  26. {
  27. class RLPStream;
  28. namespace eth
  29. {
  30. class EthereumHost;
  31. class BlockQueue;
  32. class EthereumPeer;
  33. /**
  34. * @brief Base BlockChain synchronization strategy class.
  35. * Syncs to peers and keeps up to date. Base class handles blocks downloading but does not contain any details on state transfer logic.
  36. */
  37. class BlockChainSync: public HasInvariants
  38. {
  39. public:
  40. BlockChainSync(EthereumHost& _host);
  41. ~BlockChainSync();
  42. void abortSync(); ///< Abort all sync activity
  43. /// @returns true is Sync is in progress
  44. bool isSyncing() const;
  45. /// Restart sync
  46. void restartSync();
  47. /// Called by peer to report status
  48. void onPeerStatus(std::shared_ptr<EthereumPeer> _peer);
  49. /// Called by peer once it has new block headers during sync
  50. void onPeerBlockHeaders(std::shared_ptr<EthereumPeer> _peer, RLP const& _r);
  51. /// Called by peer once it has new block bodies
  52. void onPeerBlockBodies(std::shared_ptr<EthereumPeer> _peer, RLP const& _r);
  53. /// Called by peer once it has new block bodies
  54. void onPeerNewBlock(std::shared_ptr<EthereumPeer> _peer, RLP const& _r);
  55. void onPeerNewHashes(std::shared_ptr<EthereumPeer> _peer, std::vector<std::pair<h256, u256>> const& _hashes);
  56. /// Called by peer when it is disconnecting
  57. void onPeerAborting();
  58. /// @returns Synchonization status
  59. SyncStatus status() const;
  60. static char const* stateName(SyncState _s) { return s_stateNames[static_cast<int>(_s)]; }
  61. private:
  62. /// Resume downloading after witing state
  63. void continueSync();
  64. /// Called after all blocks have been donloaded
  65. void completeSync();
  66. /// Enter waiting state
  67. void pauseSync();
  68. EthereumHost& host() { return m_host; }
  69. EthereumHost const& host() const { return m_host; }
  70. void resetSync();
  71. void syncPeer(std::shared_ptr<EthereumPeer> _peer, bool _force);
  72. void requestBlocks(std::shared_ptr<EthereumPeer> _peer);
  73. void clearPeerDownload(std::shared_ptr<EthereumPeer> _peer);
  74. void clearPeerDownload();
  75. void collectBlocks();
  76. private:
  77. struct Header
  78. {
  79. bytes data; ///< Header data
  80. h256 hash; ///< Block hash
  81. h256 parent; ///< Parent hash
  82. };
  83. /// Used to identify header by transactions and uncles hashes
  84. struct HeaderId
  85. {
  86. h256 transactionsRoot;
  87. h256 uncles;
  88. bool operator==(HeaderId const& _other) const
  89. {
  90. return transactionsRoot == _other.transactionsRoot && uncles == _other.uncles;
  91. }
  92. };
  93. struct HeaderIdHash
  94. {
  95. std::size_t operator()(const HeaderId& _k) const
  96. {
  97. size_t seed = 0;
  98. h256::hash hasher;
  99. boost::hash_combine(seed, hasher(_k.transactionsRoot));
  100. boost::hash_combine(seed, hasher(_k.uncles));
  101. return seed;
  102. }
  103. };
  104. EthereumHost& m_host;
  105. Handler<> m_bqRoomAvailable; ///< Triggered once block queue has space for more blocks
  106. mutable RecursiveMutex x_sync;
  107. SyncState m_state = SyncState::Idle; ///< Current sync state
  108. h256Hash m_knownNewHashes; ///< New hashes we know about use for logging only
  109. unsigned m_startingBlock = 0; ///< Last block number for the start of sync
  110. unsigned m_highestBlock = 0; ///< Highest block number seen
  111. std::unordered_set<unsigned> m_downloadingHeaders; ///< Set of block body numbers being downloaded
  112. std::unordered_set<unsigned> m_downloadingBodies; ///< Set of block header numbers being downloaded
  113. std::map<unsigned, std::vector<Header>> m_headers; ///< Downloaded headers
  114. std::map<unsigned, std::vector<bytes>> m_bodies; ///< Downloaded block bodies
  115. std::map<std::weak_ptr<EthereumPeer>, std::vector<unsigned>, std::owner_less<std::weak_ptr<EthereumPeer>>> m_headerSyncPeers; ///< Peers to m_downloadingSubchain number map
  116. std::map<std::weak_ptr<EthereumPeer>, std::vector<unsigned>, std::owner_less<std::weak_ptr<EthereumPeer>>> m_bodySyncPeers; ///< Peers to m_downloadingSubchain number map
  117. std::unordered_map<HeaderId, unsigned, HeaderIdHash> m_headerIdToNumber;
  118. bool m_haveCommonHeader = false; ///< True if common block for our and remote chain has been found
  119. unsigned m_lastImportedBlock = 0; ///< Last imported block number
  120. h256 m_lastImportedBlockHash; ///< Last imported block hash
  121. u256 m_syncingTotalDifficulty; ///< Highest peer difficulty
  122. private:
  123. static char const* const s_stateNames[static_cast<int>(SyncState::Size)];
  124. bool invariants() const override;
  125. void logNewBlock(h256 const& _h);
  126. };
  127. std::ostream& operator<<(std::ostream& _out, SyncStatus const& _sync);
  128. }
  129. }