net_processing.h raw

   1  // Copyright (c) 2009-2010 Satoshi Nakamoto
   2  // Copyright (c) 2009-present The Bitcoin Core developers
   3  // Distributed under the MIT software license, see the accompanying
   4  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
   5  
   6  #ifndef BITCOIN_NET_PROCESSING_H
   7  #define BITCOIN_NET_PROCESSING_H
   8  
   9  #include <consensus/amount.h>
  10  #include <net.h>
  11  #include <node/txorphanage.h>
  12  #include <node/types.h>
  13  #include <private_broadcast.h>
  14  #include <protocol.h>
  15  #include <uint256.h>
  16  #include <util/expected.h>
  17  #include <validationinterface.h>
  18  
  19  #include <atomic>
  20  #include <chrono>
  21  #include <cstdint>
  22  #include <memory>
  23  #include <optional>
  24  #include <string>
  25  #include <vector>
  26  
  27  class AddrMan;
  28  class CTxMemPool;
  29  class ChainstateManager;
  30  class BanMan;
  31  class CBlockIndex;
  32  class CScheduler;
  33  class DataStream;
  34  class uint256;
  35  
  36  namespace node {
  37  class Warnings;
  38  } // namespace node
  39  
  40  /** Whether transaction reconciliation protocol should be enabled by default. */
  41  static constexpr bool DEFAULT_TXRECONCILIATION_ENABLE{false};
  42  /** Default number of non-mempool transactions to keep around for block reconstruction. Includes
  43      orphan, replaced, and rejected transactions. */
  44  static const uint32_t DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN{100};
  45  static const bool DEFAULT_PEERBLOOMFILTERS = false;
  46  static const bool DEFAULT_PEERBLOCKFILTERS = false;
  47  /** Maximum number of outstanding CMPCTBLOCK requests for the same block. */
  48  static const unsigned int MAX_CMPCTBLOCKS_INFLIGHT_PER_BLOCK = 3;
  49  /** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends
  50   *  less than this number, we reached its tip. Changing this value is a protocol upgrade. */
  51  static const unsigned int MAX_HEADERS_RESULTS = 2000;
  52  /** The compactblocks version we support. See BIP 152. */
  53  static constexpr uint64_t CMPCTBLOCKS_VERSION{2};
  54  
  55  struct CNodeStateStats {
  56      int nSyncHeight = -1;
  57      int nCommonHeight = -1;
  58      NodeClock::duration m_ping_wait;
  59      std::vector<int> vHeightInFlight;
  60      bool m_relay_txs;
  61      int m_inv_to_send = 0;
  62      uint64_t m_last_inv_seq{0};
  63      CAmount m_fee_filter_received;
  64      uint64_t m_addr_processed = 0;
  65      uint64_t m_addr_rate_limited = 0;
  66      bool m_addr_relay_enabled{false};
  67      ServiceFlags their_services;
  68      int64_t presync_height{-1};
  69      std::chrono::seconds time_offset{0};
  70  };
  71  
  72  struct PeerManagerInfo {
  73      std::chrono::seconds median_outbound_time_offset{0s};
  74      bool ignores_incoming_txs{false};
  75      bool private_broadcast{DEFAULT_PRIVATE_BROADCAST};
  76  };
  77  
  78  class PeerManager : public CValidationInterface, public NetEventsInterface
  79  {
  80  public:
  81      struct Options {
  82          //! Whether this node is running in -blocksonly mode
  83          bool ignore_incoming_txs{DEFAULT_BLOCKSONLY};
  84          //! Whether transaction reconciliation protocol is enabled
  85          bool reconcile_txs{DEFAULT_TXRECONCILIATION_ENABLE};
  86          //! Number of non-mempool transactions to keep around for block reconstruction. Includes
  87          //! orphan, replaced, and rejected transactions.
  88          uint32_t max_extra_txs{DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN};
  89          //! Whether all P2P messages are captured to disk
  90          bool capture_messages{false};
  91          //! Whether or not the internal RNG behaves deterministically (this is
  92          //! a test-only option).
  93          bool deterministic_rng{false};
  94          //! Number of headers sent in one getheaders message result (this is
  95          //! a test-only option).
  96          uint32_t max_headers_result{MAX_HEADERS_RESULTS};
  97          //! Whether private broadcast is used for sending transactions.
  98          bool private_broadcast{DEFAULT_PRIVATE_BROADCAST};
  99      };
 100  
 101      static std::unique_ptr<PeerManager> make(CConnman& connman, AddrMan& addrman,
 102                                               BanMan* banman, ChainstateManager& chainman,
 103                                               CTxMemPool& pool, node::Warnings& warnings, Options opts);
 104      virtual ~PeerManager() = default;
 105  
 106      /**
 107       * Attempt to manually fetch block from a given peer. We must already have the header.
 108       *
 109       * @param[in]  peer_id      The peer id
 110       * @param[in]  block_index  The blockindex
 111       */
 112      virtual util::Expected<void, std::string> FetchBlock(NodeId peer_id, const CBlockIndex& block_index) = 0;
 113  
 114      /** Begin running background tasks, should only be called once */
 115      virtual void StartScheduledTasks(CScheduler& scheduler) = 0;
 116  
 117      /** Get statistics from node state */
 118      virtual bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const = 0;
 119  
 120      virtual std::vector<node::TxOrphanage::OrphanInfo> GetOrphanTransactions() = 0;
 121  
 122      /** Get peer manager info. */
 123      virtual PeerManagerInfo GetInfo() const = 0;
 124  
 125      /** Get info about transactions currently being privately broadcast. */
 126      virtual std::vector<PrivateBroadcast::TxBroadcastInfo> GetPrivateBroadcastInfo() const = 0;
 127  
 128      /**
 129       * Abort private broadcast attempts for transactions currently being privately broadcast.
 130       *
 131       * @param[in] id A transaction identifier. It will be matched against both txid and wtxid for
 132       *               all transactions in the private broadcast queue.
 133       *
 134       * @return Transactions removed from the private broadcast queue. If the provided id matches a
 135       *         txid that corresponds to multiple transactions with different wtxids, multiple
 136       *         transactions may be returned.
 137       */
 138      virtual std::vector<CTransactionRef> AbortPrivateBroadcast(const uint256& id) = 0;
 139  
 140      /**
 141       * Initiate a transaction broadcast to eligible peers.
 142       * Queue the witness transaction id to `Peer::TxRelay::m_tx_inventory_to_send`
 143       * for each peer. Later, depending on `Peer::TxRelay::m_next_inv_send_time` and if
 144       * the transaction is in the mempool, an `INV` about it may be sent to the peer.
 145       */
 146      virtual void InitiateTxBroadcastToAll(const Txid& txid, const Wtxid& wtxid) = 0;
 147  
 148      /**
 149       * Initiate a private transaction broadcast. This is done
 150       * asynchronously via short-lived connections to peers on privacy networks.
 151       * @retval node::TransactionError::OK The transaction is scheduled for private broadcast (or was already scheduled).
 152       * @retval node::TransactionError::PRIVATE_BROADCAST_FULL Rejected because the private broadcast queue is full.
 153       */
 154      [[nodiscard]] virtual node::TransactionError InitiateTxBroadcastPrivate(const CTransactionRef& tx) = 0;
 155  
 156      /** Send ping message to all peers */
 157      virtual void SendPings() = 0;
 158  
 159      /** Set the height of the best block and its time (seconds since epoch). */
 160      virtual void SetBestBlock(int height, std::chrono::seconds time) = 0;
 161  
 162      /* Public for unit testing. */
 163      virtual void UnitTestMisbehaving(NodeId peer_id) = 0;
 164  
 165      /**
 166       * Evict extra outbound peers. If we think our tip may be stale, connect to an extra outbound.
 167       * Public for unit testing.
 168       */
 169      virtual void CheckForStaleTipAndEvictPeers() = 0;
 170  
 171      /** This function is used for testing the stale tip eviction logic, see denialofservice_tests.cpp */
 172      virtual void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds) = 0;
 173  
 174      /**
 175       * Gets the set of service flags which are "desirable" for a given peer.
 176       *
 177       * These are the flags which are required for a peer to support for them
 178       * to be "interesting" to us, ie for us to wish to use one of our few
 179       * outbound connection slots for or for us to wish to prioritize keeping
 180       * their connection around.
 181       *
 182       * Relevant service flags may be peer- and state-specific in that the
 183       * version of the peer may determine which flags are required (eg in the
 184       * case of NODE_NETWORK_LIMITED where we seek out NODE_NETWORK peers
 185       * unless they set NODE_NETWORK_LIMITED and we are out of IBD, in which
 186       * case NODE_NETWORK_LIMITED suffices).
 187       *
 188       * Thus, generally, avoid calling with 'services' == NODE_NONE, unless
 189       * state-specific flags must absolutely be avoided. When called with
 190       * 'services' == NODE_NONE, the returned desirable service flags are
 191       * guaranteed to not change dependent on state - ie they are suitable for
 192       * use when describing peers which we know to be desirable, but for which
 193       * we do not have a confirmed set of service flags.
 194      */
 195      virtual ServiceFlags GetDesirableServiceFlags(ServiceFlags services) const = 0;
 196  };
 197  
 198  #endif // BITCOIN_NET_PROCESSING_H
 199