Bitcoin Core 22.99.0
P2P Digital Currency
net_processing.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2020 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#include <net_processing.h>
7
8#include <addrman.h>
9#include <banman.h>
10#include <blockencodings.h>
11#include <blockfilter.h>
12#include <chainparams.h>
13#include <consensus/amount.h>
15#include <deploymentstatus.h>
16#include <hash.h>
18#include <merkleblock.h>
19#include <netbase.h>
20#include <netmessagemaker.h>
21#include <node/blockstorage.h>
22#include <policy/fees.h>
23#include <policy/policy.h>
24#include <primitives/block.h>
26#include <random.h>
27#include <reverse_iterator.h>
28#include <scheduler.h>
29#include <streams.h>
30#include <sync.h>
31#include <tinyformat.h>
32#include <txmempool.h>
33#include <txorphanage.h>
34#include <txrequest.h>
35#include <util/check.h> // For NDEBUG compile time check
36#include <util/strencodings.h>
37#include <util/system.h>
38#include <util/trace.h>
39#include <validation.h>
40
41#include <algorithm>
42#include <memory>
43#include <optional>
44#include <typeinfo>
45
47static constexpr auto RELAY_TX_CACHE_TIME = 15min;
49static constexpr auto UNCONDITIONAL_RELAY_DELAY = 2min;
52static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_BASE = 15min;
53static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER = 1ms;
59static constexpr int64_t CHAIN_SYNC_TIMEOUT = 20 * 60; // 20 minutes
61static constexpr int64_t STALE_CHECK_INTERVAL = 10 * 60; // 10 minutes
63static constexpr int64_t EXTRA_PEER_CHECK_INTERVAL = 45;
65static constexpr int64_t MINIMUM_CONNECT_TIME = 30;
67static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL;
70static constexpr int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60;
73static constexpr int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60;
75static constexpr std::chrono::minutes PING_INTERVAL{2};
77static const unsigned int MAX_LOCATOR_SZ = 101;
79static const unsigned int MAX_INV_SZ = 50000;
82static constexpr int32_t MAX_PEER_TX_REQUEST_IN_FLIGHT = 100;
87static constexpr int32_t MAX_PEER_TX_ANNOUNCEMENTS = 5000;
89static constexpr auto TXID_RELAY_DELAY = std::chrono::seconds{2};
91static constexpr auto NONPREF_PEER_TX_DELAY = std::chrono::seconds{2};
93static constexpr auto OVERLOADED_PEER_TX_DELAY = std::chrono::seconds{2};
95static constexpr std::chrono::microseconds GETDATA_TX_INTERVAL{std::chrono::seconds{60}};
97static const unsigned int MAX_GETDATA_SZ = 1000;
99static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
101static constexpr auto BLOCK_STALLING_TIMEOUT = 2s;
104static const unsigned int MAX_HEADERS_RESULTS = 2000;
107static const int MAX_CMPCTBLOCK_DEPTH = 5;
109static const int MAX_BLOCKTXN_DEPTH = 10;
114static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
116static constexpr double BLOCK_DOWNLOAD_TIMEOUT_BASE = 1;
118static constexpr double BLOCK_DOWNLOAD_TIMEOUT_PER_PEER = 0.5;
120static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8;
122static const int MAX_UNCONNECTING_HEADERS = 10;
124static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS = 288;
126static constexpr auto AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL = 24h;
128static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL = 30s;
131static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL = 5s;
135static constexpr auto OUTBOUND_INVENTORY_BROADCAST_INTERVAL = 2s;
138static constexpr unsigned int INVENTORY_BROADCAST_PER_SECOND = 7;
142static constexpr unsigned int INVENTORY_MAX_RECENT_RELAY = 3500;
147static_assert(INVENTORY_MAX_RECENT_RELAY >= INVENTORY_BROADCAST_PER_SECOND * UNCONDITIONAL_RELAY_DELAY / std::chrono::seconds{1}, "INVENTORY_RELAY_MAX too low");
149static constexpr auto AVG_FEEFILTER_BROADCAST_INTERVAL = 10min;
151static constexpr auto MAX_FEEFILTER_CHANGE_DELAY = 5min;
153static constexpr uint32_t MAX_GETCFILTERS_SIZE = 1000;
155static constexpr uint32_t MAX_GETCFHEADERS_SIZE = 2000;
157static constexpr size_t MAX_PCT_ADDR_TO_SEND = 23;
159static constexpr size_t MAX_ADDR_TO_SEND{1000};
162static constexpr double MAX_ADDR_RATE_PER_SECOND{0.1};
167
168// Internal stuff
169namespace {
171struct QueuedBlock {
173 const CBlockIndex* pindex;
175 std::unique_ptr<PartiallyDownloadedBlock> partialBlock;
176};
177
190struct Peer {
192 const NodeId m_id{0};
193
195 Mutex m_misbehavior_mutex;
197 int m_misbehavior_score GUARDED_BY(m_misbehavior_mutex){0};
199 bool m_should_discourage GUARDED_BY(m_misbehavior_mutex){false};
200
202 Mutex m_block_inv_mutex;
206 std::vector<uint256> m_blocks_for_inv_relay GUARDED_BY(m_block_inv_mutex);
210 std::vector<uint256> m_blocks_for_headers_relay GUARDED_BY(m_block_inv_mutex);
215 uint256 m_continuation_block GUARDED_BY(m_block_inv_mutex) {};
216
218 std::atomic<int> m_starting_height{-1};
219
221 std::atomic<uint64_t> m_ping_nonce_sent{0};
223 std::atomic<std::chrono::microseconds> m_ping_start{0us};
225 std::atomic<bool> m_ping_queued{false};
226
228 std::vector<CAddress> m_addrs_to_send;
238 std::unique_ptr<CRollingBloomFilter> m_addr_known;
253 std::atomic_bool m_addr_relay_enabled{false};
255 bool m_getaddr_sent{false};
257 mutable Mutex m_addr_send_times_mutex;
259 std::chrono::microseconds m_next_addr_send GUARDED_BY(m_addr_send_times_mutex){0};
261 std::chrono::microseconds m_next_local_addr_send GUARDED_BY(m_addr_send_times_mutex){0};
264 std::atomic_bool m_wants_addrv2{false};
266 bool m_getaddr_recvd{false};
269 double m_addr_token_bucket{1.0};
271 std::chrono::microseconds m_addr_token_timestamp{GetTime<std::chrono::microseconds>()};
273 std::atomic<uint64_t> m_addr_rate_limited{0};
275 std::atomic<uint64_t> m_addr_processed{0};
276
278 std::set<uint256> m_orphan_work_set GUARDED_BY(g_cs_orphans);
279
281 Mutex m_getdata_requests_mutex;
283 std::deque<CInv> m_getdata_requests GUARDED_BY(m_getdata_requests_mutex);
284
285 explicit Peer(NodeId id)
286 : m_id(id)
287 {}
288};
289
290using PeerRef = std::shared_ptr<Peer>;
291
292class PeerManagerImpl final : public PeerManager
293{
294public:
295 PeerManagerImpl(const CChainParams& chainparams, CConnman& connman, AddrMan& addrman,
296 BanMan* banman, ChainstateManager& chainman,
297 CTxMemPool& pool, bool ignore_incoming_txs);
298
300 void BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindexConnected) override;
301 void BlockDisconnected(const std::shared_ptr<const CBlock> &block, const CBlockIndex* pindex) override;
302 void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override;
303 void BlockChecked(const CBlock& block, const BlockValidationState& state) override;
304 void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) override;
305
307 void InitializeNode(CNode* pnode) override;
308 void FinalizeNode(const CNode& node) override;
309 bool ProcessMessages(CNode* pfrom, std::atomic<bool>& interrupt) override;
310 bool SendMessages(CNode* pto) override EXCLUSIVE_LOCKS_REQUIRED(pto->cs_sendProcessing);
311
313 void StartScheduledTasks(CScheduler& scheduler) override;
314 void CheckForStaleTipAndEvictPeers() override;
315 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const override;
316 bool IgnoresIncomingTxs() override { return m_ignore_incoming_txs; }
317 void SendPings() override;
318 void RelayTransaction(const uint256& txid, const uint256& wtxid) override;
319 void SetBestHeight(int height) override { m_best_height = height; };
320 void Misbehaving(const NodeId pnode, const int howmuch, const std::string& message) override;
321 void ProcessMessage(CNode& pfrom, const std::string& msg_type, CDataStream& vRecv,
322 const std::chrono::microseconds time_received, const std::atomic<bool>& interruptMsgProc) override;
323
324private:
325 void _RelayTransaction(const uint256& txid, const uint256& wtxid)
327
329 void ConsiderEviction(CNode& pto, int64_t time_in_seconds) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
330
332 void EvictExtraOutboundPeers(int64_t time_in_seconds) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
333
335 void ReattemptInitialBroadcast(CScheduler& scheduler);
336
339 PeerRef GetPeerRef(NodeId id) const;
340
343 PeerRef RemovePeer(NodeId id);
344
355 bool MaybePunishNodeForBlock(NodeId nodeid, const BlockValidationState& state,
356 bool via_compact_block, const std::string& message = "");
357
363 bool MaybePunishNodeForTx(NodeId nodeid, const TxValidationState& state, const std::string& message = "");
364
371 bool MaybeDiscourageAndDisconnect(CNode& pnode, Peer& peer);
372
373 void ProcessOrphanTx(std::set<uint256>& orphan_work_set) EXCLUSIVE_LOCKS_REQUIRED(cs_main, g_cs_orphans);
375 void ProcessHeadersMessage(CNode& pfrom, const Peer& peer,
376 const std::vector<CBlockHeader>& headers,
377 bool via_compact_block);
378
379 void SendBlockTransactions(CNode& pfrom, const CBlock& block, const BlockTransactionsRequest& req);
380
384 void AddTxAnnouncement(const CNode& node, const GenTxid& gtxid, std::chrono::microseconds current_time)
386
388 void PushNodeVersion(CNode& pnode, int64_t nTime);
389
394 void MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::microseconds now);
395
397 void MaybeSendAddr(CNode& node, Peer& peer, std::chrono::microseconds current_time);
398
406 void RelayAddress(NodeId originator, const CAddress& addr, bool fReachable);
407
409 void MaybeSendFeefilter(CNode& node, std::chrono::microseconds current_time) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
410
411 const CChainParams& m_chainparams;
412 CConnman& m_connman;
413 AddrMan& m_addrman;
415 BanMan* const m_banman;
416 ChainstateManager& m_chainman;
417 CTxMemPool& m_mempool;
418 TxRequestTracker m_txrequest GUARDED_BY(::cs_main);
419
421 std::atomic<int> m_best_height{-1};
422
424 int64_t m_stale_tip_check_time{0};
425
427 const bool m_ignore_incoming_txs;
428
431 bool m_initial_sync_finished{false};
432
435 mutable Mutex m_peer_mutex;
442 std::map<NodeId, PeerRef> m_peer_map GUARDED_BY(m_peer_mutex);
443
445 int nSyncStarted GUARDED_BY(cs_main) = 0;
446
453 std::map<uint256, std::pair<NodeId, bool>> mapBlockSource GUARDED_BY(cs_main);
454
456 int m_wtxid_relay_peers GUARDED_BY(cs_main) = 0;
457
459 int m_outbound_peers_with_protect_from_disconnect GUARDED_BY(cs_main) = 0;
460
461 bool AlreadyHaveTx(const GenTxid& gtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
462
497 CRollingBloomFilter m_recent_rejects GUARDED_BY(::cs_main){120'000, 0.000'001};
498 uint256 hashRecentRejectsChainTip GUARDED_BY(cs_main);
499
500 /*
501 * Filter for transactions that have been recently confirmed.
502 * We use this to avoid requesting transactions that have already been
503 * confirnmed.
504 *
505 * Blocks don't typically have more than 4000 transactions, so this should
506 * be at least six blocks (~1 hr) worth of transactions that we can store,
507 * inserting both a txid and wtxid for every observed transaction.
508 * If the number of transactions appearing in a block goes up, or if we are
509 * seeing getdata requests more than an hour after initial announcement, we
510 * can increase this number.
511 * The false positive rate of 1/1M should come out to less than 1
512 * transaction per day that would be inadvertently ignored (which is the
513 * same probability that we have in the reject filter).
514 */
515 Mutex m_recent_confirmed_transactions_mutex;
516 CRollingBloomFilter m_recent_confirmed_transactions GUARDED_BY(m_recent_confirmed_transactions_mutex){48'000, 0.000'001};
517
519 bool IsBlockRequested(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
520
525 void RemoveBlockRequest(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
526
527 /* Mark a block as in flight
528 * Returns false, still setting pit, if the block was already in flight from the same peer
529 * pit will only be valid as long as the same cs_main lock is being held
530 */
531 bool BlockRequested(NodeId nodeid, const CBlockIndex& block, std::list<QueuedBlock>::iterator** pit = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
532
533 bool TipMayBeStale() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
534
538 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
539
540 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight GUARDED_BY(cs_main);
541
543 std::atomic<int64_t> m_last_tip_update{0};
544
546 CTransactionRef FindTxForGetData(const CNode& peer, const GenTxid& gtxid, const std::chrono::seconds mempool_req, const std::chrono::seconds now) LOCKS_EXCLUDED(cs_main);
547
548 void ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic<bool>& interruptMsgProc) EXCLUSIVE_LOCKS_REQUIRED(peer.m_getdata_requests_mutex) LOCKS_EXCLUDED(::cs_main);
549
551 void ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing);
552
554 typedef std::map<uint256, CTransactionRef> MapRelay;
555 MapRelay mapRelay GUARDED_BY(cs_main);
557 std::deque<std::pair<std::chrono::microseconds, MapRelay::iterator>> g_relay_expiration GUARDED_BY(cs_main);
558
565 void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
566
568 std::list<NodeId> lNodesAnnouncingHeaderAndIDs GUARDED_BY(cs_main);
569
571 int m_peers_downloading_from GUARDED_BY(cs_main) = 0;
572
574 TxOrphanage m_orphanage;
575
576 void AddToCompactExtraTransactions(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(g_cs_orphans);
577
581 std::vector<std::pair<uint256, CTransactionRef>> vExtraTxnForCompact GUARDED_BY(g_cs_orphans);
583 size_t vExtraTxnForCompactIt GUARDED_BY(g_cs_orphans) = 0;
584
586 void ProcessBlockAvailability(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
588 void UpdateBlockAvailability(NodeId nodeid, const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
589 bool CanDirectFetch() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
590
597 bool BlockRequestAllowed(const CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
598 bool AlreadyHaveBlock(const uint256& block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
599 void ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& inv);
600
615 bool PrepareBlockFilterRequest(CNode& peer,
616 BlockFilterType filter_type, uint32_t start_height,
617 const uint256& stop_hash, uint32_t max_height_diff,
618 const CBlockIndex*& stop_index,
619 BlockFilterIndex*& filter_index);
620
629 void ProcessGetCFilters(CNode& peer, CDataStream& vRecv);
630
639 void ProcessGetCFHeaders(CNode& peer, CDataStream& vRecv);
640
649 void ProcessGetCFCheckPt(CNode& peer, CDataStream& vRecv);
650
657 bool SetupAddressRelay(const CNode& node, Peer& peer);
658};
659} // namespace
660
661namespace {
663 int nPreferredDownload GUARDED_BY(cs_main) = 0;
664} // namespace
665
666namespace {
673struct CNodeState {
675 const CBlockIndex* pindexBestKnownBlock{nullptr};
677 uint256 hashLastUnknownBlock{};
679 const CBlockIndex* pindexLastCommonBlock{nullptr};
681 const CBlockIndex* pindexBestHeaderSent{nullptr};
683 int nUnconnectingHeaders{0};
685 bool fSyncStarted{false};
687 std::chrono::microseconds m_headers_sync_timeout{0us};
689 std::chrono::microseconds m_stalling_since{0us};
690 std::list<QueuedBlock> vBlocksInFlight;
692 std::chrono::microseconds m_downloading_since{0us};
693 int nBlocksInFlight{0};
695 bool fPreferredDownload{false};
697 bool fPreferHeaders{false};
699 bool fPreferHeaderAndIDs{false};
705 bool fProvidesHeaderAndIDs{false};
707 bool fHaveWitness{false};
709 bool fWantsCmpctWitness{false};
714 bool fSupportsDesiredCmpctVersion{false};
715
740 struct ChainSyncTimeoutState {
742 int64_t m_timeout{0};
744 const CBlockIndex* m_work_header{nullptr};
746 bool m_sent_getheaders{false};
748 bool m_protect{false};
749 };
750
751 ChainSyncTimeoutState m_chain_sync;
752
754 int64_t m_last_block_announcement{0};
755
757 const bool m_is_inbound;
758
760 CRollingBloomFilter m_recently_announced_invs = CRollingBloomFilter{INVENTORY_MAX_RECENT_RELAY, 0.000001};
761
763 bool m_wtxid_relay{false};
764
765 CNodeState(bool is_inbound) : m_is_inbound(is_inbound) {}
766};
767
769static std::map<NodeId, CNodeState> mapNodeState GUARDED_BY(cs_main);
770
771static CNodeState *State(NodeId pnode) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
772 std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
773 if (it == mapNodeState.end())
774 return nullptr;
775 return &it->second;
776}
777
783static bool IsAddrCompatible(const Peer& peer, const CAddress& addr)
784{
785 return peer.m_wants_addrv2 || addr.IsAddrV1Compatible();
786}
787
788static void AddAddressKnown(Peer& peer, const CAddress& addr)
789{
790 assert(peer.m_addr_known);
791 peer.m_addr_known->insert(addr.GetKey());
792}
793
794static void PushAddress(Peer& peer, const CAddress& addr, FastRandomContext& insecure_rand)
795{
796 // Known checking here is only to save space from duplicates.
797 // Before sending, we'll filter it again for known addresses that were
798 // added after addresses were pushed.
799 assert(peer.m_addr_known);
800 if (addr.IsValid() && !peer.m_addr_known->contains(addr.GetKey()) && IsAddrCompatible(peer, addr)) {
801 if (peer.m_addrs_to_send.size() >= MAX_ADDR_TO_SEND) {
802 peer.m_addrs_to_send[insecure_rand.randrange(peer.m_addrs_to_send.size())] = addr;
803 } else {
804 peer.m_addrs_to_send.push_back(addr);
805 }
806 }
807}
808
809static void UpdatePreferredDownload(const CNode& node, CNodeState* state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
810{
811 nPreferredDownload -= state->fPreferredDownload;
812
813 // Whether this node should be marked as a preferred download node.
814 state->fPreferredDownload = (!node.IsInboundConn() || node.HasPermission(NetPermissionFlags::NoBan)) && !node.IsAddrFetchConn() && !node.fClient;
815
816 nPreferredDownload += state->fPreferredDownload;
817}
818
819bool PeerManagerImpl::IsBlockRequested(const uint256& hash)
820{
821 return mapBlocksInFlight.find(hash) != mapBlocksInFlight.end();
822}
823
824void PeerManagerImpl::RemoveBlockRequest(const uint256& hash)
825{
826 auto it = mapBlocksInFlight.find(hash);
827 if (it == mapBlocksInFlight.end()) {
828 // Block was not requested
829 return;
830 }
831
832 auto [node_id, list_it] = it->second;
833 CNodeState *state = State(node_id);
834 assert(state != nullptr);
835
836 if (state->vBlocksInFlight.begin() == list_it) {
837 // First block on the queue was received, update the start download time for the next one
838 state->m_downloading_since = std::max(state->m_downloading_since, GetTime<std::chrono::microseconds>());
839 }
840 state->vBlocksInFlight.erase(list_it);
841
842 state->nBlocksInFlight--;
843 if (state->nBlocksInFlight == 0) {
844 // Last validated block on the queue was received.
845 m_peers_downloading_from--;
846 }
847 state->m_stalling_since = 0us;
848 mapBlocksInFlight.erase(it);
849}
850
851bool PeerManagerImpl::BlockRequested(NodeId nodeid, const CBlockIndex& block, std::list<QueuedBlock>::iterator** pit)
852{
853 const uint256& hash{block.GetBlockHash()};
854
855 CNodeState *state = State(nodeid);
856 assert(state != nullptr);
857
858 // Short-circuit most stuff in case it is from the same node
859 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
860 if (itInFlight != mapBlocksInFlight.end() && itInFlight->second.first == nodeid) {
861 if (pit) {
862 *pit = &itInFlight->second.second;
863 }
864 return false;
865 }
866
867 // Make sure it's not listed somewhere already.
868 RemoveBlockRequest(hash);
869
870 std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(),
871 {&block, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&m_mempool) : nullptr)});
872 state->nBlocksInFlight++;
873 if (state->nBlocksInFlight == 1) {
874 // We're starting a block download (batch) from this peer.
875 state->m_downloading_since = GetTime<std::chrono::microseconds>();
876 m_peers_downloading_from++;
877 }
878 itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it))).first;
879 if (pit) {
880 *pit = &itInFlight->second.second;
881 }
882 return true;
883}
884
885void PeerManagerImpl::MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid)
886{
888
889 // Never request high-bandwidth mode from peers if we're blocks-only. Our
890 // mempool will not contain the transactions necessary to reconstruct the
891 // compact block.
892 if (m_ignore_incoming_txs) return;
893
894 CNodeState* nodestate = State(nodeid);
895 if (!nodestate || !nodestate->fSupportsDesiredCmpctVersion) {
896 // Never ask from peers who can't provide witnesses.
897 return;
898 }
899 if (nodestate->fProvidesHeaderAndIDs) {
900 int num_outbound_hb_peers = 0;
901 for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin(); it != lNodesAnnouncingHeaderAndIDs.end(); it++) {
902 if (*it == nodeid) {
903 lNodesAnnouncingHeaderAndIDs.erase(it);
904 lNodesAnnouncingHeaderAndIDs.push_back(nodeid);
905 return;
906 }
907 CNodeState *state = State(*it);
908 if (state != nullptr && !state->m_is_inbound) ++num_outbound_hb_peers;
909 }
910 if (nodestate->m_is_inbound) {
911 // If we're adding an inbound HB peer, make sure we're not removing
912 // our last outbound HB peer in the process.
913 if (lNodesAnnouncingHeaderAndIDs.size() >= 3 && num_outbound_hb_peers == 1) {
914 CNodeState *remove_node = State(lNodesAnnouncingHeaderAndIDs.front());
915 if (remove_node != nullptr && !remove_node->m_is_inbound) {
916 // Put the HB outbound peer in the second slot, so that it
917 // doesn't get removed.
918 std::swap(lNodesAnnouncingHeaderAndIDs.front(), *std::next(lNodesAnnouncingHeaderAndIDs.begin()));
919 }
920 }
921 }
922 m_connman.ForNode(nodeid, [this](CNode* pfrom) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
924 uint64_t nCMPCTBLOCKVersion = 2;
925 if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
926 // As per BIP152, we only get 3 of our peers to announce
927 // blocks using compact encodings.
928 m_connman.ForNode(lNodesAnnouncingHeaderAndIDs.front(), [this, nCMPCTBLOCKVersion](CNode* pnodeStop){
929 m_connman.PushMessage(pnodeStop, CNetMsgMaker(pnodeStop->GetCommonVersion()).Make(NetMsgType::SENDCMPCT, /*fAnnounceUsingCMPCTBLOCK=*/false, nCMPCTBLOCKVersion));
930 // save BIP152 bandwidth state: we select peer to be low-bandwidth
931 pnodeStop->m_bip152_highbandwidth_to = false;
932 return true;
933 });
934 lNodesAnnouncingHeaderAndIDs.pop_front();
935 }
936 m_connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetCommonVersion()).Make(NetMsgType::SENDCMPCT, /*fAnnounceUsingCMPCTBLOCK=*/true, nCMPCTBLOCKVersion));
937 // save BIP152 bandwidth state: we select peer to be high-bandwidth
938 pfrom->m_bip152_highbandwidth_to = true;
939 lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId());
940 return true;
941 });
942 }
943}
944
945bool PeerManagerImpl::TipMayBeStale()
946{
948 const Consensus::Params& consensusParams = m_chainparams.GetConsensus();
949 if (m_last_tip_update == 0) {
950 m_last_tip_update = GetTime();
951 }
952 return m_last_tip_update < GetTime() - consensusParams.nPowTargetSpacing * 3 && mapBlocksInFlight.empty();
953}
954
955bool PeerManagerImpl::CanDirectFetch()
956{
957 return m_chainman.ActiveChain().Tip()->GetBlockTime() > GetAdjustedTime() - m_chainparams.GetConsensus().nPowTargetSpacing * 20;
958}
959
960static bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
961{
962 if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
963 return true;
964 if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight))
965 return true;
966 return false;
967}
968
969void PeerManagerImpl::ProcessBlockAvailability(NodeId nodeid) {
970 CNodeState *state = State(nodeid);
971 assert(state != nullptr);
972
973 if (!state->hashLastUnknownBlock.IsNull()) {
974 const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(state->hashLastUnknownBlock);
975 if (pindex && pindex->nChainWork > 0) {
976 if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
977 state->pindexBestKnownBlock = pindex;
978 }
979 state->hashLastUnknownBlock.SetNull();
980 }
981 }
982}
983
984void PeerManagerImpl::UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
985 CNodeState *state = State(nodeid);
986 assert(state != nullptr);
987
988 ProcessBlockAvailability(nodeid);
989
990 const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hash);
991 if (pindex && pindex->nChainWork > 0) {
992 // An actually better block was announced.
993 if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
994 state->pindexBestKnownBlock = pindex;
995 }
996 } else {
997 // An unknown block was announced; just assume that the latest one is the best one.
998 state->hashLastUnknownBlock = hash;
999 }
1000}
1001
1002void PeerManagerImpl::FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller)
1003{
1004 if (count == 0)
1005 return;
1006
1007 vBlocks.reserve(vBlocks.size() + count);
1008 CNodeState *state = State(nodeid);
1009 assert(state != nullptr);
1010
1011 // Make sure pindexBestKnownBlock is up to date, we'll need it.
1012 ProcessBlockAvailability(nodeid);
1013
1014 if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->nChainWork < m_chainman.ActiveChain().Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < nMinimumChainWork) {
1015 // This peer has nothing interesting.
1016 return;
1017 }
1018
1019 if (state->pindexLastCommonBlock == nullptr) {
1020 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
1021 // Guessing wrong in either direction is not a problem.
1022 state->pindexLastCommonBlock = m_chainman.ActiveChain()[std::min(state->pindexBestKnownBlock->nHeight, m_chainman.ActiveChain().Height())];
1023 }
1024
1025 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
1026 // of its current tip anymore. Go back enough to fix that.
1027 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
1028 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
1029 return;
1030
1031 const Consensus::Params& consensusParams = m_chainparams.GetConsensus();
1032 std::vector<const CBlockIndex*> vToFetch;
1033 const CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
1034 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
1035 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
1036 // download that next block if the window were 1 larger.
1037 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
1038 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
1039 NodeId waitingfor = -1;
1040 while (pindexWalk->nHeight < nMaxHeight) {
1041 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
1042 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
1043 // as iterating over ~100 CBlockIndex* entries anyway.
1044 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
1045 vToFetch.resize(nToFetch);
1046 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
1047 vToFetch[nToFetch - 1] = pindexWalk;
1048 for (unsigned int i = nToFetch - 1; i > 0; i--) {
1049 vToFetch[i - 1] = vToFetch[i]->pprev;
1050 }
1051
1052 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
1053 // are not yet downloaded and not in flight to vBlocks. In the meantime, update
1054 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
1055 // already part of our chain (and therefore don't need it even if pruned).
1056 for (const CBlockIndex* pindex : vToFetch) {
1057 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
1058 // We consider the chain that this peer is on invalid.
1059 return;
1060 }
1061 if (!State(nodeid)->fHaveWitness && DeploymentActiveAt(*pindex, consensusParams, Consensus::DEPLOYMENT_SEGWIT)) {
1062 // We wouldn't download this block or its descendants from this peer.
1063 return;
1064 }
1065 if (pindex->nStatus & BLOCK_HAVE_DATA || m_chainman.ActiveChain().Contains(pindex)) {
1066 if (pindex->HaveTxsDownloaded())
1067 state->pindexLastCommonBlock = pindex;
1068 } else if (!IsBlockRequested(pindex->GetBlockHash())) {
1069 // The block is not already downloaded, and not yet in flight.
1070 if (pindex->nHeight > nWindowEnd) {
1071 // We reached the end of the window.
1072 if (vBlocks.size() == 0 && waitingfor != nodeid) {
1073 // We aren't able to fetch anything, but we would be if the download window was one larger.
1074 nodeStaller = waitingfor;
1075 }
1076 return;
1077 }
1078 vBlocks.push_back(pindex);
1079 if (vBlocks.size() == count) {
1080 return;
1081 }
1082 } else if (waitingfor == -1) {
1083 // This is the first already-in-flight block.
1084 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
1085 }
1086 }
1087 }
1088}
1089
1090} // namespace
1091
1092void PeerManagerImpl::PushNodeVersion(CNode& pnode, int64_t nTime)
1093{
1094 // Note that pnode->GetLocalServices() is a reflection of the local
1095 // services we were offering when the CNode object was created for this
1096 // peer.
1097 uint64_t my_services{pnode.GetLocalServices()};
1098 uint64_t nonce = pnode.GetLocalNonce();
1099 const int nNodeStartingHeight{m_best_height};
1100 NodeId nodeid = pnode.GetId();
1101 CAddress addr = pnode.addr;
1102
1103 CService addr_you = addr.IsRoutable() && !IsProxy(addr) && addr.IsAddrV1Compatible() ? addr : CService();
1104 uint64_t your_services{addr.nServices};
1105
1106 const bool tx_relay = !m_ignore_incoming_txs && pnode.m_tx_relay != nullptr;
1107 m_connman.PushMessage(&pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERSION, PROTOCOL_VERSION, my_services, nTime,
1108 your_services, addr_you, // Together the pre-version-31402 serialization of CAddress "addrYou" (without nTime)
1109 my_services, CService(), // Together the pre-version-31402 serialization of CAddress "addrMe" (without nTime)
1110 nonce, strSubVersion, nNodeStartingHeight, tx_relay));
1111
1112 if (fLogIPs) {
1113 LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, them=%s, txrelay=%d, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addr_you.ToString(), tx_relay, nodeid);
1114 } else {
1115 LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, txrelay=%d, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, tx_relay, nodeid);
1116 }
1117}
1118
1119void PeerManagerImpl::AddTxAnnouncement(const CNode& node, const GenTxid& gtxid, std::chrono::microseconds current_time)
1120{
1121 AssertLockHeld(::cs_main); // For m_txrequest
1122 NodeId nodeid = node.GetId();
1123 if (!node.HasPermission(NetPermissionFlags::Relay) && m_txrequest.Count(nodeid) >= MAX_PEER_TX_ANNOUNCEMENTS) {
1124 // Too many queued announcements from this peer
1125 return;
1126 }
1127 const CNodeState* state = State(nodeid);
1128
1129 // Decide the TxRequestTracker parameters for this announcement:
1130 // - "preferred": if fPreferredDownload is set (= outbound, or NetPermissionFlags::NoBan permission)
1131 // - "reqtime": current time plus delays for:
1132 // - NONPREF_PEER_TX_DELAY for announcements from non-preferred connections
1133 // - TXID_RELAY_DELAY for txid announcements while wtxid peers are available
1134 // - OVERLOADED_PEER_TX_DELAY for announcements from peers which have at least
1135 // MAX_PEER_TX_REQUEST_IN_FLIGHT requests in flight (and don't have NetPermissionFlags::Relay).
1136 auto delay = std::chrono::microseconds{0};
1137 const bool preferred = state->fPreferredDownload;
1138 if (!preferred) delay += NONPREF_PEER_TX_DELAY;
1139 if (!gtxid.IsWtxid() && m_wtxid_relay_peers > 0) delay += TXID_RELAY_DELAY;
1140 const bool overloaded = !node.HasPermission(NetPermissionFlags::Relay) &&
1141 m_txrequest.CountInFlight(nodeid) >= MAX_PEER_TX_REQUEST_IN_FLIGHT;
1142 if (overloaded) delay += OVERLOADED_PEER_TX_DELAY;
1143 m_txrequest.ReceivedInv(nodeid, gtxid, preferred, current_time + delay);
1144}
1145
1146// This function is used for testing the stale tip eviction logic, see
1147// denialofservice_tests.cpp
1148void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds)
1149{
1150 LOCK(cs_main);
1151 CNodeState *state = State(node);
1152 if (state) state->m_last_block_announcement = time_in_seconds;
1153}
1154
1155void PeerManagerImpl::InitializeNode(CNode *pnode)
1156{
1157 NodeId nodeid = pnode->GetId();
1158 {
1159 LOCK(cs_main);
1160 mapNodeState.emplace_hint(mapNodeState.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(pnode->IsInboundConn()));
1161 assert(m_txrequest.Count(nodeid) == 0);
1162 }
1163 {
1164 PeerRef peer = std::make_shared<Peer>(nodeid);
1165 LOCK(m_peer_mutex);
1166 m_peer_map.emplace_hint(m_peer_map.end(), nodeid, std::move(peer));
1167 }
1168 if (!pnode->IsInboundConn()) {
1169 PushNodeVersion(*pnode, GetTime());
1170 }
1171}
1172
1173void PeerManagerImpl::ReattemptInitialBroadcast(CScheduler& scheduler)
1174{
1175 std::set<uint256> unbroadcast_txids = m_mempool.GetUnbroadcastTxs();
1176
1177 for (const auto& txid : unbroadcast_txids) {
1178 CTransactionRef tx = m_mempool.get(txid);
1179
1180 if (tx != nullptr) {
1181 LOCK(cs_main);
1182 _RelayTransaction(txid, tx->GetWitnessHash());
1183 } else {
1184 m_mempool.RemoveUnbroadcastTx(txid, true);
1185 }
1186 }
1187
1188 // Schedule next run for 10-15 minutes in the future.
1189 // We add randomness on every cycle to avoid the possibility of P2P fingerprinting.
1190 const std::chrono::milliseconds delta = std::chrono::minutes{10} + GetRandMillis(std::chrono::minutes{5});
1191 scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta);
1192}
1193
1194void PeerManagerImpl::FinalizeNode(const CNode& node)
1195{
1196 NodeId nodeid = node.GetId();
1197 int misbehavior{0};
1198 {
1199 LOCK(cs_main);
1200 {
1201 // We remove the PeerRef from g_peer_map here, but we don't always
1202 // destruct the Peer. Sometimes another thread is still holding a
1203 // PeerRef, so the refcount is >= 1. Be careful not to do any
1204 // processing here that assumes Peer won't be changed before it's
1205 // destructed.
1206 PeerRef peer = RemovePeer(nodeid);
1207 assert(peer != nullptr);
1208 misbehavior = WITH_LOCK(peer->m_misbehavior_mutex, return peer->m_misbehavior_score);
1209 }
1210 CNodeState *state = State(nodeid);
1211 assert(state != nullptr);
1212
1213 if (state->fSyncStarted)
1214 nSyncStarted--;
1215
1216 for (const QueuedBlock& entry : state->vBlocksInFlight) {
1217 mapBlocksInFlight.erase(entry.pindex->GetBlockHash());
1218 }
1219 WITH_LOCK(g_cs_orphans, m_orphanage.EraseForPeer(nodeid));
1220 m_txrequest.DisconnectedPeer(nodeid);
1221 nPreferredDownload -= state->fPreferredDownload;
1222 m_peers_downloading_from -= (state->nBlocksInFlight != 0);
1223 assert(m_peers_downloading_from >= 0);
1224 m_outbound_peers_with_protect_from_disconnect -= state->m_chain_sync.m_protect;
1225 assert(m_outbound_peers_with_protect_from_disconnect >= 0);
1226 m_wtxid_relay_peers -= state->m_wtxid_relay;
1227 assert(m_wtxid_relay_peers >= 0);
1228
1229 mapNodeState.erase(nodeid);
1230
1231 if (mapNodeState.empty()) {
1232 // Do a consistency check after the last peer is removed.
1233 assert(mapBlocksInFlight.empty());
1234 assert(nPreferredDownload == 0);
1235 assert(m_peers_downloading_from == 0);
1236 assert(m_outbound_peers_with_protect_from_disconnect == 0);
1237 assert(m_wtxid_relay_peers == 0);
1238 assert(m_txrequest.Size() == 0);
1239 assert(m_orphanage.Size() == 0);
1240 }
1241 } // cs_main
1242 if (node.fSuccessfullyConnected && misbehavior == 0 &&
1243 !node.IsBlockOnlyConn() && !node.IsInboundConn()) {
1244 // Only change visible addrman state for full outbound peers. We don't
1245 // call Connected() for feeler connections since they don't have
1246 // fSuccessfullyConnected set.
1247 m_addrman.Connected(node.addr);
1248 }
1249 LogPrint(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid);
1250}
1251
1252PeerRef PeerManagerImpl::GetPeerRef(NodeId id) const
1253{
1254 LOCK(m_peer_mutex);
1255 auto it = m_peer_map.find(id);
1256 return it != m_peer_map.end() ? it->second : nullptr;
1257}
1258
1259PeerRef PeerManagerImpl::RemovePeer(NodeId id)
1260{
1261 PeerRef ret;
1262 LOCK(m_peer_mutex);
1263 auto it = m_peer_map.find(id);
1264 if (it != m_peer_map.end()) {
1265 ret = std::move(it->second);
1266 m_peer_map.erase(it);
1267 }
1268 return ret;
1269}
1270
1271bool PeerManagerImpl::GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const
1272{
1273 {
1274 LOCK(cs_main);
1275 CNodeState* state = State(nodeid);
1276 if (state == nullptr)
1277 return false;
1278 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
1279 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
1280 for (const QueuedBlock& queue : state->vBlocksInFlight) {
1281 if (queue.pindex)
1282 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
1283 }
1284 }
1285
1286 PeerRef peer = GetPeerRef(nodeid);
1287 if (peer == nullptr) return false;
1288 stats.m_starting_height = peer->m_starting_height;
1289 // It is common for nodes with good ping times to suddenly become lagged,
1290 // due to a new block arriving or other large transfer.
1291 // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
1292 // since pingtime does not update until the ping is complete, which might take a while.
1293 // So, if a ping is taking an unusually long time in flight,
1294 // the caller can immediately detect that this is happening.
1295 std::chrono::microseconds ping_wait{0};
1296 if ((0 != peer->m_ping_nonce_sent) && (0 != peer->m_ping_start.load().count())) {
1297 ping_wait = GetTime<std::chrono::microseconds>() - peer->m_ping_start.load();
1298 }
1299
1300 stats.m_ping_wait = ping_wait;
1301 stats.m_addr_processed = peer->m_addr_processed.load();
1302 stats.m_addr_rate_limited = peer->m_addr_rate_limited.load();
1303 stats.m_addr_relay_enabled = peer->m_addr_relay_enabled.load();
1304
1305 return true;
1306}
1307
1308void PeerManagerImpl::AddToCompactExtraTransactions(const CTransactionRef& tx)
1309{
1310 size_t max_extra_txn = gArgs.GetIntArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN);
1311 if (max_extra_txn <= 0)
1312 return;
1313 if (!vExtraTxnForCompact.size())
1314 vExtraTxnForCompact.resize(max_extra_txn);
1315 vExtraTxnForCompact[vExtraTxnForCompactIt] = std::make_pair(tx->GetWitnessHash(), tx);
1316 vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % max_extra_txn;
1317}
1318
1319void PeerManagerImpl::Misbehaving(const NodeId pnode, const int howmuch, const std::string& message)
1320{
1321 assert(howmuch > 0);
1322
1323 PeerRef peer = GetPeerRef(pnode);
1324 if (peer == nullptr) return;
1325
1326 LOCK(peer->m_misbehavior_mutex);
1327 const int score_before{peer->m_misbehavior_score};
1328 peer->m_misbehavior_score += howmuch;
1329 const int score_now{peer->m_misbehavior_score};
1330
1331 const std::string message_prefixed = message.empty() ? "" : (": " + message);
1332 std::string warning;
1333
1334 if (score_now >= DISCOURAGEMENT_THRESHOLD && score_before < DISCOURAGEMENT_THRESHOLD) {
1335 warning = " DISCOURAGE THRESHOLD EXCEEDED";
1336 peer->m_should_discourage = true;
1337 }
1338
1339 LogPrint(BCLog::NET, "Misbehaving: peer=%d (%d -> %d)%s%s\n",
1340 pnode, score_before, score_now, warning, message_prefixed);
1341}
1342
1343bool PeerManagerImpl::MaybePunishNodeForBlock(NodeId nodeid, const BlockValidationState& state,
1344 bool via_compact_block, const std::string& message)
1345{
1346 switch (state.GetResult()) {
1348 break;
1349 // The node is providing invalid data:
1352 if (!via_compact_block) {
1353 Misbehaving(nodeid, 100, message);
1354 return true;
1355 }
1356 break;
1358 {
1359 LOCK(cs_main);
1360 CNodeState *node_state = State(nodeid);
1361 if (node_state == nullptr) {
1362 break;
1363 }
1364
1365 // Discourage outbound (but not inbound) peers if on an invalid chain.
1366 // Exempt HB compact block peers. Manual connections are always protected from discouragement.
1367 if (!via_compact_block && !node_state->m_is_inbound) {
1368 Misbehaving(nodeid, 100, message);
1369 return true;
1370 }
1371 break;
1372 }
1376 Misbehaving(nodeid, 100, message);
1377 return true;
1378 // Conflicting (but not necessarily invalid) data or different policy:
1380 // TODO: Handle this much more gracefully (10 DoS points is super arbitrary)
1381 Misbehaving(nodeid, 10, message);
1382 return true;
1385 break;
1386 }
1387 if (message != "") {
1388 LogPrint(BCLog::NET, "peer=%d: %s\n", nodeid, message);
1389 }
1390 return false;
1391}
1392
1393bool PeerManagerImpl::MaybePunishNodeForTx(NodeId nodeid, const TxValidationState& state, const std::string& message)
1394{
1395 switch (state.GetResult()) {
1397 break;
1398 // The node is providing invalid data:
1400 Misbehaving(nodeid, 100, message);
1401 return true;
1402 // Conflicting (but not necessarily invalid) data or different policy:
1412 break;
1413 }
1414 if (message != "") {
1415 LogPrint(BCLog::NET, "peer=%d: %s\n", nodeid, message);
1416 }
1417 return false;
1418}
1419
1420bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex* pindex)
1421{
1423 if (m_chainman.ActiveChain().Contains(pindex)) return true;
1424 return pindex->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != nullptr) &&
1427}
1428
1429std::unique_ptr<PeerManager> PeerManager::make(const CChainParams& chainparams, CConnman& connman, AddrMan& addrman,
1430 BanMan* banman, ChainstateManager& chainman,
1431 CTxMemPool& pool, bool ignore_incoming_txs)
1432{
1433 return std::make_unique<PeerManagerImpl>(chainparams, connman, addrman, banman, chainman, pool, ignore_incoming_txs);
1434}
1435
1436PeerManagerImpl::PeerManagerImpl(const CChainParams& chainparams, CConnman& connman, AddrMan& addrman,
1437 BanMan* banman, ChainstateManager& chainman,
1438 CTxMemPool& pool, bool ignore_incoming_txs)
1439 : m_chainparams(chainparams),
1440 m_connman(connman),
1441 m_addrman(addrman),
1442 m_banman(banman),
1443 m_chainman(chainman),
1444 m_mempool(pool),
1445 m_ignore_incoming_txs(ignore_incoming_txs)
1446{
1447}
1448
1449void PeerManagerImpl::StartScheduledTasks(CScheduler& scheduler)
1450{
1451 // Stale tip checking and peer eviction are on two different timers, but we
1452 // don't want them to get out of sync due to drift in the scheduler, so we
1453 // combine them in one function and schedule at the quicker (peer-eviction)
1454 // timer.
1455 static_assert(EXTRA_PEER_CHECK_INTERVAL < STALE_CHECK_INTERVAL, "peer eviction timer should be less than stale tip check timer");
1456 scheduler.scheduleEvery([this] { this->CheckForStaleTipAndEvictPeers(); }, std::chrono::seconds{EXTRA_PEER_CHECK_INTERVAL});
1457
1458 // schedule next run for 10-15 minutes in the future
1459 const std::chrono::milliseconds delta = std::chrono::minutes{10} + GetRandMillis(std::chrono::minutes{5});
1460 scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta);
1461}
1462
1468void PeerManagerImpl::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex)
1469{
1470 m_orphanage.EraseForBlock(*pblock);
1471 m_last_tip_update = GetTime();
1472
1473 {
1474 LOCK(m_recent_confirmed_transactions_mutex);
1475 for (const auto& ptx : pblock->vtx) {
1476 m_recent_confirmed_transactions.insert(ptx->GetHash());
1477 if (ptx->GetHash() != ptx->GetWitnessHash()) {
1478 m_recent_confirmed_transactions.insert(ptx->GetWitnessHash());
1479 }
1480 }
1481 }
1482 {
1483 LOCK(cs_main);
1484 for (const auto& ptx : pblock->vtx) {
1485 m_txrequest.ForgetTxHash(ptx->GetHash());
1486 m_txrequest.ForgetTxHash(ptx->GetWitnessHash());
1487 }
1488 }
1489}
1490
1491void PeerManagerImpl::BlockDisconnected(const std::shared_ptr<const CBlock> &block, const CBlockIndex* pindex)
1492{
1493 // To avoid relay problems with transactions that were previously
1494 // confirmed, clear our filter of recently confirmed transactions whenever
1495 // there's a reorg.
1496 // This means that in a 1-block reorg (where 1 block is disconnected and
1497 // then another block reconnected), our filter will drop to having only one
1498 // block's worth of transactions in it, but that should be fine, since
1499 // presumably the most common case of relaying a confirmed transaction
1500 // should be just after a new block containing it is found.
1501 LOCK(m_recent_confirmed_transactions_mutex);
1502 m_recent_confirmed_transactions.reset();
1503}
1504
1505// All of the following cache a recent block, and are protected by cs_most_recent_block
1507static std::shared_ptr<const CBlock> most_recent_block GUARDED_BY(cs_most_recent_block);
1508static std::shared_ptr<const CBlockHeaderAndShortTxIDs> most_recent_compact_block GUARDED_BY(cs_most_recent_block);
1509static uint256 most_recent_block_hash GUARDED_BY(cs_most_recent_block);
1510static bool fWitnessesPresentInMostRecentCompactBlock GUARDED_BY(cs_most_recent_block);
1511
1516void PeerManagerImpl::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock)
1517{
1518 std::shared_ptr<const CBlockHeaderAndShortTxIDs> pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs> (*pblock, true);
1519 const CNetMsgMaker msgMaker(PROTOCOL_VERSION);
1520
1521 LOCK(cs_main);
1522
1523 static int nHighestFastAnnounce = 0;
1524 if (pindex->nHeight <= nHighestFastAnnounce)
1525 return;
1526 nHighestFastAnnounce = pindex->nHeight;
1527
1528 bool fWitnessEnabled = DeploymentActiveAt(*pindex, m_chainparams.GetConsensus(), Consensus::DEPLOYMENT_SEGWIT);
1529 uint256 hashBlock(pblock->GetHash());
1530
1531 {
1533 most_recent_block_hash = hashBlock;
1534 most_recent_block = pblock;
1535 most_recent_compact_block = pcmpctblock;
1536 fWitnessesPresentInMostRecentCompactBlock = fWitnessEnabled;
1537 }
1538
1539 m_connman.ForEachNode([this, &pcmpctblock, pindex, &msgMaker, fWitnessEnabled, &hashBlock](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
1541
1542 // TODO: Avoid the repeated-serialization here
1544 return;
1545 ProcessBlockAvailability(pnode->GetId());
1546 CNodeState &state = *State(pnode->GetId());
1547 // If the peer has, or we announced to them the previous block already,
1548 // but we don't think they have this one, go ahead and announce it
1549 if (state.fPreferHeaderAndIDs && (!fWitnessEnabled || state.fWantsCmpctWitness) &&
1550 !PeerHasHeader(&state, pindex) && PeerHasHeader(&state, pindex->pprev)) {
1551
1552 LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerManager::NewPoWValidBlock",
1553 hashBlock.ToString(), pnode->GetId());
1554 m_connman.PushMessage(pnode, msgMaker.Make(NetMsgType::CMPCTBLOCK, *pcmpctblock));
1555 state.pindexBestHeaderSent = pindex;
1556 }
1557 });
1558}
1559
1564void PeerManagerImpl::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
1565{
1566 SetBestHeight(pindexNew->nHeight);
1567 SetServiceFlagsIBDCache(!fInitialDownload);
1568
1569 // Don't relay inventory during initial block download.
1570 if (fInitialDownload) return;
1571
1572 // Find the hashes of all blocks that weren't previously in the best chain.
1573 std::vector<uint256> vHashes;
1574 const CBlockIndex *pindexToAnnounce = pindexNew;
1575 while (pindexToAnnounce != pindexFork) {
1576 vHashes.push_back(pindexToAnnounce->GetBlockHash());
1577 pindexToAnnounce = pindexToAnnounce->pprev;
1578 if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {
1579 // Limit announcements in case of a huge reorganization.
1580 // Rely on the peer's synchronization mechanism in that case.
1581 break;
1582 }
1583 }
1584
1585 {
1586 LOCK(m_peer_mutex);
1587 for (auto& it : m_peer_map) {
1588 Peer& peer = *it.second;
1589 LOCK(peer.m_block_inv_mutex);
1590 for (const uint256& hash : reverse_iterate(vHashes)) {
1591 peer.m_blocks_for_headers_relay.push_back(hash);
1592 }
1593 }
1594 }
1595
1596 m_connman.WakeMessageHandler();
1597}
1598
1603void PeerManagerImpl::BlockChecked(const CBlock& block, const BlockValidationState& state)
1604{
1605 LOCK(cs_main);
1606
1607 const uint256 hash(block.GetHash());
1608 std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash);
1609
1610 // If the block failed validation, we know where it came from and we're still connected
1611 // to that peer, maybe punish.
1612 if (state.IsInvalid() &&
1613 it != mapBlockSource.end() &&
1614 State(it->second.first)) {
1615 MaybePunishNodeForBlock(/*nodeid=*/ it->second.first, state, /*via_compact_block=*/ !it->second.second);
1616 }
1617 // Check that:
1618 // 1. The block is valid
1619 // 2. We're not in initial block download
1620 // 3. This is currently the best block we're aware of. We haven't updated
1621 // the tip yet so we have no way to check this directly here. Instead we
1622 // just check that there are currently no other blocks in flight.
1623 else if (state.IsValid() &&
1624 !m_chainman.ActiveChainstate().IsInitialBlockDownload() &&
1625 mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
1626 if (it != mapBlockSource.end()) {
1627 MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first);
1628 }
1629 }
1630 if (it != mapBlockSource.end())
1631 mapBlockSource.erase(it);
1632}
1633
1635//
1636// Messages
1637//
1638
1639
1640bool PeerManagerImpl::AlreadyHaveTx(const GenTxid& gtxid)
1641{
1642 if (m_chainman.ActiveChain().Tip()->GetBlockHash() != hashRecentRejectsChainTip) {
1643 // If the chain tip has changed previously rejected transactions
1644 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
1645 // or a double-spend. Reset the rejects filter and give those
1646 // txs a second chance.
1647 hashRecentRejectsChainTip = m_chainman.ActiveChain().Tip()->GetBlockHash();
1648 m_recent_rejects.reset();
1649 }
1650
1651 const uint256& hash = gtxid.GetHash();
1652
1653 if (m_orphanage.HaveTx(gtxid)) return true;
1654
1655 {
1656 LOCK(m_recent_confirmed_transactions_mutex);
1657 if (m_recent_confirmed_transactions.contains(hash)) return true;
1658 }
1659
1660 return m_recent_rejects.contains(hash) || m_mempool.exists(gtxid);
1661}
1662
1663bool PeerManagerImpl::AlreadyHaveBlock(const uint256& block_hash)
1664{
1665 return m_chainman.m_blockman.LookupBlockIndex(block_hash) != nullptr;
1666}
1667
1668void PeerManagerImpl::SendPings()
1669{
1670 LOCK(m_peer_mutex);
1671 for(auto& it : m_peer_map) it.second->m_ping_queued = true;
1672}
1673
1674void PeerManagerImpl::RelayTransaction(const uint256& txid, const uint256& wtxid)
1675{
1676 WITH_LOCK(cs_main, _RelayTransaction(txid, wtxid););
1677}
1678
1679void PeerManagerImpl::_RelayTransaction(const uint256& txid, const uint256& wtxid)
1680{
1681 m_connman.ForEachNode([&txid, &wtxid](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
1683
1684 CNodeState* state = State(pnode->GetId());
1685 if (state == nullptr) return;
1686 if (state->m_wtxid_relay) {
1687 pnode->PushTxInventory(wtxid);
1688 } else {
1689 pnode->PushTxInventory(txid);
1690 }
1691 });
1692}
1693
1694void PeerManagerImpl::RelayAddress(NodeId originator,
1695 const CAddress& addr,
1696 bool fReachable)
1697{
1698 // We choose the same nodes within a given 24h window (if the list of connected
1699 // nodes does not change) and we don't relay to nodes that already know an
1700 // address. So within 24h we will likely relay a given address once. This is to
1701 // prevent a peer from unjustly giving their address better propagation by sending
1702 // it to us repeatedly.
1703
1704 if (!fReachable && !addr.IsRelayable()) return;
1705
1706 // Relay to a limited number of other nodes
1707 // Use deterministic randomness to send to the same nodes for 24 hours
1708 // at a time so the m_addr_knowns of the chosen nodes prevent repeats
1709 uint64_t hashAddr = addr.GetHash();
1710 const CSipHasher hasher = m_connman.GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY).Write(hashAddr << 32).Write((GetTime() + hashAddr) / (24 * 60 * 60));
1711 FastRandomContext insecure_rand;
1712
1713 // Relay reachable addresses to 2 peers. Unreachable addresses are relayed randomly to 1 or 2 peers.
1714 unsigned int nRelayNodes = (fReachable || (hasher.Finalize() & 1)) ? 2 : 1;
1715
1716 std::array<std::pair<uint64_t, Peer*>, 2> best{{{0, nullptr}, {0, nullptr}}};
1717 assert(nRelayNodes <= best.size());
1718
1719 LOCK(m_peer_mutex);
1720
1721 for (auto& [id, peer] : m_peer_map) {
1722 if (peer->m_addr_relay_enabled && id != originator && IsAddrCompatible(*peer, addr)) {
1723 uint64_t hashKey = CSipHasher(hasher).Write(id).Finalize();
1724 for (unsigned int i = 0; i < nRelayNodes; i++) {
1725 if (hashKey > best[i].first) {
1726 std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1);
1727 best[i] = std::make_pair(hashKey, peer.get());
1728 break;
1729 }
1730 }
1731 }
1732 };
1733
1734 for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
1735 PushAddress(*best[i].second, addr, insecure_rand);
1736 }
1737}
1738
1739void PeerManagerImpl::ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& inv)
1740{
1741 std::shared_ptr<const CBlock> a_recent_block;
1742 std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
1743 bool fWitnessesPresentInARecentCompactBlock;
1744 {
1746 a_recent_block = most_recent_block;
1747 a_recent_compact_block = most_recent_compact_block;
1748 fWitnessesPresentInARecentCompactBlock = fWitnessesPresentInMostRecentCompactBlock;
1749 }
1750
1751 bool need_activate_chain = false;
1752 {
1753 LOCK(cs_main);
1754 const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash);
1755 if (pindex) {
1756 if (pindex->HaveTxsDownloaded() && !pindex->IsValid(BLOCK_VALID_SCRIPTS) &&
1757 pindex->IsValid(BLOCK_VALID_TREE)) {
1758 // If we have the block and all of its parents, but have not yet validated it,
1759 // we might be in the middle of connecting it (ie in the unlock of cs_main
1760 // before ActivateBestChain but after AcceptBlock).
1761 // In this case, we need to run ActivateBestChain prior to checking the relay
1762 // conditions below.
1763 need_activate_chain = true;
1764 }
1765 }
1766 } // release cs_main before calling ActivateBestChain
1767 if (need_activate_chain) {
1769 if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) {
1770 LogPrint(BCLog::NET, "failed to activate chain (%s)\n", state.ToString());
1771 }
1772 }
1773
1774 LOCK(cs_main);
1775 const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash);
1776 if (!pindex) {
1777 return;
1778 }
1779 if (!BlockRequestAllowed(pindex)) {
1780 LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom.GetId());
1781 return;
1782 }
1783 const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
1784 // disconnect node in case we have reached the outbound limit for serving historical blocks
1785 if (m_connman.OutboundTargetReached(true) &&
1786 (((pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - pindex->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.IsMsgFilteredBlk()) &&
1787 !pfrom.HasPermission(NetPermissionFlags::Download) // nodes with the download permission may exceed target
1788 ) {
1789 LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom.GetId());
1790 pfrom.fDisconnect = true;
1791 return;
1792 }
1793 // Avoid leaking prune-height by never sending blocks below the NODE_NETWORK_LIMITED threshold
1795 (((pfrom.GetLocalServices() & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((pfrom.GetLocalServices() & NODE_NETWORK) != NODE_NETWORK) && (m_chainman.ActiveChain().Tip()->nHeight - pindex->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2 /* add two blocks buffer extension for possible races */) )
1796 )) {
1797 LogPrint(BCLog::NET, "Ignore block request below NODE_NETWORK_LIMITED threshold, disconnect peer=%d\n", pfrom.GetId());
1798 //disconnect node and prevent it from stalling (would otherwise wait for the missing block)
1799 pfrom.fDisconnect = true;
1800 return;
1801 }
1802 // Pruned nodes may have deleted the block, so check whether
1803 // it's available before trying to send.
1804 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) {
1805 return;
1806 }
1807 std::shared_ptr<const CBlock> pblock;
1808 if (a_recent_block && a_recent_block->GetHash() == pindex->GetBlockHash()) {
1809 pblock = a_recent_block;
1810 } else if (inv.IsMsgWitnessBlk()) {
1811 // Fast-path: in this case it is possible to serve the block directly from disk,
1812 // as the network format matches the format on disk
1813 std::vector<uint8_t> block_data;
1814 if (!ReadRawBlockFromDisk(block_data, pindex, m_chainparams.MessageStart())) {
1815 assert(!"cannot load block from disk");
1816 }
1817 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::BLOCK, MakeSpan(block_data)));
1818 // Don't set pblock as we've sent the block
1819 } else {
1820 // Send block from disk
1821 std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
1822 if (!ReadBlockFromDisk(*pblockRead, pindex, m_chainparams.GetConsensus())) {
1823 assert(!"cannot load block from disk");
1824 }
1825 pblock = pblockRead;
1826 }
1827 if (pblock) {
1828 if (inv.IsMsgBlk()) {
1829 m_connman.PushMessage(&pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::BLOCK, *pblock));
1830 } else if (inv.IsMsgWitnessBlk()) {
1831 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::BLOCK, *pblock));
1832 } else if (inv.IsMsgFilteredBlk()) {
1833 bool sendMerkleBlock = false;
1834 CMerkleBlock merkleBlock;
1835 if (pfrom.m_tx_relay != nullptr) {
1836 LOCK(pfrom.m_tx_relay->cs_filter);
1837 if (pfrom.m_tx_relay->pfilter) {
1838 sendMerkleBlock = true;
1839 merkleBlock = CMerkleBlock(*pblock, *pfrom.m_tx_relay->pfilter);
1840 }
1841 }
1842 if (sendMerkleBlock) {
1843 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::MERKLEBLOCK, merkleBlock));
1844 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
1845 // This avoids hurting performance by pointlessly requiring a round-trip
1846 // Note that there is currently no way for a node to request any single transactions we didn't send here -
1847 // they must either disconnect and retry or request the full block.
1848 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
1849 // however we MUST always provide at least what the remote peer needs
1850 typedef std::pair<unsigned int, uint256> PairType;
1851 for (PairType& pair : merkleBlock.vMatchedTxn)
1852 m_connman.PushMessage(&pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::TX, *pblock->vtx[pair.first]));
1853 }
1854 // else
1855 // no response
1856 } else if (inv.IsMsgCmpctBlk()) {
1857 // If a peer is asking for old blocks, we're almost guaranteed
1858 // they won't have a useful mempool to match against a compact block,
1859 // and we don't feel like constructing the object for them, so
1860 // instead we respond with the full, non-compact block.
1861 bool fPeerWantsWitness = State(pfrom.GetId())->fWantsCmpctWitness;
1862 int nSendFlags = fPeerWantsWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
1863 if (CanDirectFetch() && pindex->nHeight >= m_chainman.ActiveChain().Height() - MAX_CMPCTBLOCK_DEPTH) {
1864 if ((fPeerWantsWitness || !fWitnessesPresentInARecentCompactBlock) && a_recent_compact_block && a_recent_compact_block->header.GetHash() == pindex->GetBlockHash()) {
1865 m_connman.PushMessage(&pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *a_recent_compact_block));
1866 } else {
1867 CBlockHeaderAndShortTxIDs cmpctblock(*pblock, fPeerWantsWitness);
1868 m_connman.PushMessage(&pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
1869 }
1870 } else {
1871 m_connman.PushMessage(&pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCK, *pblock));
1872 }
1873 }
1874 }
1875
1876 {
1877 LOCK(peer.m_block_inv_mutex);
1878 // Trigger the peer node to send a getblocks request for the next batch of inventory
1879 if (inv.hash == peer.m_continuation_block) {
1880 // Send immediately. This must send even if redundant,
1881 // and we want it right after the last block so they don't
1882 // wait for other stuff first.
1883 std::vector<CInv> vInv;
1884 vInv.push_back(CInv(MSG_BLOCK, m_chainman.ActiveChain().Tip()->GetBlockHash()));
1885 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::INV, vInv));
1886 peer.m_continuation_block.SetNull();
1887 }
1888 }
1889}
1890
1891CTransactionRef PeerManagerImpl::FindTxForGetData(const CNode& peer, const GenTxid& gtxid, const std::chrono::seconds mempool_req, const std::chrono::seconds now)
1892{
1893 auto txinfo = m_mempool.info(gtxid);
1894 if (txinfo.tx) {
1895 // If a TX could have been INVed in reply to a MEMPOOL request,
1896 // or is older than UNCONDITIONAL_RELAY_DELAY, permit the request
1897 // unconditionally.
1898 if ((mempool_req.count() && txinfo.m_time <= mempool_req) || txinfo.m_time <= now - UNCONDITIONAL_RELAY_DELAY) {
1899 return std::move(txinfo.tx);
1900 }
1901 }
1902
1903 {
1904 LOCK(cs_main);
1905 // Otherwise, the transaction must have been announced recently.
1906 if (State(peer.GetId())->m_recently_announced_invs.contains(gtxid.GetHash())) {
1907 // If it was, it can be relayed from either the mempool...
1908 if (txinfo.tx) return std::move(txinfo.tx);
1909 // ... or the relay pool.
1910 auto mi = mapRelay.find(gtxid.GetHash());
1911 if (mi != mapRelay.end()) return mi->second;
1912 }
1913 }
1914
1915 return {};
1916}
1917
1918void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic<bool>& interruptMsgProc)
1919{
1921
1922 std::deque<CInv>::iterator it = peer.m_getdata_requests.begin();
1923 std::vector<CInv> vNotFound;
1924 const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
1925
1926 const std::chrono::seconds now = GetTime<std::chrono::seconds>();
1927 // Get last mempool request time
1928 const std::chrono::seconds mempool_req = pfrom.m_tx_relay != nullptr ? pfrom.m_tx_relay->m_last_mempool_req.load()
1929 : std::chrono::seconds::min();
1930
1931 // Process as many TX items from the front of the getdata queue as
1932 // possible, since they're common and it's efficient to batch process
1933 // them.
1934 while (it != peer.m_getdata_requests.end() && it->IsGenTxMsg()) {
1935 if (interruptMsgProc) return;
1936 // The send buffer provides backpressure. If there's no space in
1937 // the buffer, pause processing until the next call.
1938 if (pfrom.fPauseSend) break;
1939
1940 const CInv &inv = *it++;
1941
1942 if (pfrom.m_tx_relay == nullptr) {
1943 // Ignore GETDATA requests for transactions from blocks-only peers.
1944 continue;
1945 }
1946
1947 CTransactionRef tx = FindTxForGetData(pfrom, ToGenTxid(inv), mempool_req, now);
1948 if (tx) {
1949 // WTX and WITNESS_TX imply we serialize with witness
1950 int nSendFlags = (inv.IsMsgTx() ? SERIALIZE_TRANSACTION_NO_WITNESS : 0);
1951 m_connman.PushMessage(&pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *tx));
1952 m_mempool.RemoveUnbroadcastTx(tx->GetHash());
1953 // As we're going to send tx, make sure its unconfirmed parents are made requestable.
1954 std::vector<uint256> parent_ids_to_add;
1955 {
1956 LOCK(m_mempool.cs);
1957 auto txiter = m_mempool.GetIter(tx->GetHash());
1958 if (txiter) {
1959 const CTxMemPoolEntry::Parents& parents = (*txiter)->GetMemPoolParentsConst();
1960 parent_ids_to_add.reserve(parents.size());
1961 for (const CTxMemPoolEntry& parent : parents) {
1962 if (parent.GetTime() > now - UNCONDITIONAL_RELAY_DELAY) {
1963 parent_ids_to_add.push_back(parent.GetTx().GetHash());
1964 }
1965 }
1966 }
1967 }
1968 for (const uint256& parent_txid : parent_ids_to_add) {
1969 // Relaying a transaction with a recent but unconfirmed parent.
1970 if (WITH_LOCK(pfrom.m_tx_relay->cs_tx_inventory, return !pfrom.m_tx_relay->filterInventoryKnown.contains(parent_txid))) {
1971 LOCK(cs_main);
1972 State(pfrom.GetId())->m_recently_announced_invs.insert(parent_txid);
1973 }
1974 }
1975 } else {
1976 vNotFound.push_back(inv);
1977 }
1978 }
1979
1980 // Only process one BLOCK item per call, since they're uncommon and can be
1981 // expensive to process.
1982 if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) {
1983 const CInv &inv = *it++;
1984 if (inv.IsGenBlkMsg()) {
1985 ProcessGetBlockData(pfrom, peer, inv);
1986 }
1987 // else: If the first item on the queue is an unknown type, we erase it
1988 // and continue processing the queue on the next call.
1989 }
1990
1991 peer.m_getdata_requests.erase(peer.m_getdata_requests.begin(), it);
1992
1993 if (!vNotFound.empty()) {
1994 // Let the peer know that we didn't find what it asked for, so it doesn't
1995 // have to wait around forever.
1996 // SPV clients care about this message: it's needed when they are
1997 // recursively walking the dependencies of relevant unconfirmed
1998 // transactions. SPV clients want to do that because they want to know
1999 // about (and store and rebroadcast and risk analyze) the dependencies
2000 // of transactions relevant to them, without having to download the
2001 // entire memory pool.
2002 // Also, other nodes can use these messages to automatically request a
2003 // transaction from some other peer that annnounced it, and stop
2004 // waiting for us to respond.
2005 // In normal operation, we often send NOTFOUND messages for parents of
2006 // transactions that we relay; if a peer is missing a parent, they may
2007 // assume we have them and request the parents from us.
2008 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::NOTFOUND, vNotFound));
2009 }
2010}
2011
2012static uint32_t GetFetchFlags(const CNode& pfrom) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
2013 uint32_t nFetchFlags = 0;
2014 if (State(pfrom.GetId())->fHaveWitness) {
2015 nFetchFlags |= MSG_WITNESS_FLAG;
2016 }
2017 return nFetchFlags;
2018}
2019
2020void PeerManagerImpl::SendBlockTransactions(CNode& pfrom, const CBlock& block, const BlockTransactionsRequest& req)
2021{
2022 BlockTransactions resp(req);
2023 for (size_t i = 0; i < req.indexes.size(); i++) {
2024 if (req.indexes[i] >= block.vtx.size()) {
2025 Misbehaving(pfrom.GetId(), 100, "getblocktxn with out-of-bounds tx indices");
2026 return;
2027 }
2028 resp.txn[i] = block.vtx[req.indexes[i]];
2029 }
2030 LOCK(cs_main);
2031 const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
2032 int nSendFlags = State(pfrom.GetId())->fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
2033 m_connman.PushMessage(&pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCKTXN, resp));
2034}
2035
2036void PeerManagerImpl::ProcessHeadersMessage(CNode& pfrom, const Peer& peer,
2037 const std::vector<CBlockHeader>& headers,
2038 bool via_compact_block)
2039{
2040 const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
2041 size_t nCount = headers.size();
2042
2043 if (nCount == 0) {
2044 // Nothing interesting. Stop asking this peers for more headers.
2045 return;
2046 }
2047
2048 bool received_new_header = false;
2049 const CBlockIndex *pindexLast = nullptr;
2050 {
2051 LOCK(cs_main);
2052 CNodeState *nodestate = State(pfrom.GetId());
2053
2054 // If this looks like it could be a block announcement (nCount <
2055 // MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that
2056 // don't connect:
2057 // - Send a getheaders message in response to try to connect the chain.
2058 // - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
2059 // don't connect before giving DoS points
2060 // - Once a headers message is received that is valid and does connect,
2061 // nUnconnectingHeaders gets reset back to 0.
2062 if (!m_chainman.m_blockman.LookupBlockIndex(headers[0].hashPrevBlock) && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
2063 nodestate->nUnconnectingHeaders++;
2064 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETHEADERS, m_chainman.ActiveChain().GetLocator(pindexBestHeader), uint256()));
2065 LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
2066 headers[0].GetHash().ToString(),
2067 headers[0].hashPrevBlock.ToString(),
2069 pfrom.GetId(), nodestate->nUnconnectingHeaders);
2070 // Set hashLastUnknownBlock for this peer, so that if we
2071 // eventually get the headers - even from a different peer -
2072 // we can use this peer to download.
2073 UpdateBlockAvailability(pfrom.GetId(), headers.back().GetHash());
2074
2075 if (nodestate->nUnconnectingHeaders % MAX_UNCONNECTING_HEADERS == 0) {
2076 Misbehaving(pfrom.GetId(), 20, strprintf("%d non-connecting headers", nodestate->nUnconnectingHeaders));
2077 }
2078 return;
2079 }
2080
2081 uint256 hashLastBlock;
2082 for (const CBlockHeader& header : headers) {
2083 if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
2084 Misbehaving(pfrom.GetId(), 20, "non-continuous headers sequence");
2085 return;
2086 }
2087 hashLastBlock = header.GetHash();
2088 }
2089
2090 // If we don't have the last header, then they'll have given us
2091 // something new (if these headers are valid).
2092 if (!m_chainman.m_blockman.LookupBlockIndex(hashLastBlock)) {
2093 received_new_header = true;
2094 }
2095 }
2096
2098 if (!m_chainman.ProcessNewBlockHeaders(headers, state, m_chainparams, &pindexLast)) {
2099 if (state.IsInvalid()) {
2100 MaybePunishNodeForBlock(pfrom.GetId(), state, via_compact_block, "invalid header received");
2101 return;
2102 }
2103 }
2104
2105 {
2106 LOCK(cs_main);
2107 CNodeState *nodestate = State(pfrom.GetId());
2108 if (nodestate->nUnconnectingHeaders > 0) {
2109 LogPrint(BCLog::NET, "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom.GetId(), nodestate->nUnconnectingHeaders);
2110 }
2111 nodestate->nUnconnectingHeaders = 0;
2112
2113 assert(pindexLast);
2114 UpdateBlockAvailability(pfrom.GetId(), pindexLast->GetBlockHash());
2115
2116 // From here, pindexBestKnownBlock should be guaranteed to be non-null,
2117 // because it is set in UpdateBlockAvailability. Some nullptr checks
2118 // are still present, however, as belt-and-suspenders.
2119
2120 if (received_new_header && pindexLast->nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) {
2121 nodestate->m_last_block_announcement = GetTime();
2122 }
2123
2124 if (nCount == MAX_HEADERS_RESULTS) {
2125 // Headers message had its maximum size; the peer may have more headers.
2126 // TODO: optimize: if pindexLast is an ancestor of m_chainman.ActiveChain().Tip or pindexBestHeader, continue
2127 // from there instead.
2128 LogPrint(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n",
2129 pindexLast->nHeight, pfrom.GetId(), peer.m_starting_height);
2130 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETHEADERS, m_chainman.ActiveChain().GetLocator(pindexLast), uint256()));
2131 }
2132
2133 // If this set of headers is valid and ends in a block with at least as
2134 // much work as our tip, download as much as possible.
2135 if (CanDirectFetch() && pindexLast->IsValid(BLOCK_VALID_TREE) && m_chainman.ActiveChain().Tip()->nChainWork <= pindexLast->nChainWork) {
2136 std::vector<const CBlockIndex*> vToFetch;
2137 const CBlockIndex *pindexWalk = pindexLast;
2138 // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
2139 while (pindexWalk && !m_chainman.ActiveChain().Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
2140 if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
2141 !IsBlockRequested(pindexWalk->GetBlockHash()) &&
2142 (!DeploymentActiveAt(*pindexWalk, m_chainparams.GetConsensus(), Consensus::DEPLOYMENT_SEGWIT) || State(pfrom.GetId())->fHaveWitness)) {
2143 // We don't have this block, and it's not yet in flight.
2144 vToFetch.push_back(pindexWalk);
2145 }
2146 pindexWalk = pindexWalk->pprev;
2147 }
2148 // If pindexWalk still isn't on our main chain, we're looking at a
2149 // very large reorg at a time we think we're close to caught up to
2150 // the main chain -- this shouldn't really happen. Bail out on the
2151 // direct fetch and rely on parallel download instead.
2152 if (!m_chainman.ActiveChain().Contains(pindexWalk)) {
2153 LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n",
2154 pindexLast->GetBlockHash().ToString(),
2155 pindexLast->nHeight);
2156 } else {
2157 std::vector<CInv> vGetData;
2158 // Download as much as possible, from earliest to latest.
2159 for (const CBlockIndex *pindex : reverse_iterate(vToFetch)) {
2160 if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
2161 // Can't download any more from this peer
2162 break;
2163 }
2164 uint32_t nFetchFlags = GetFetchFlags(pfrom);
2165 vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
2166 BlockRequested(pfrom.GetId(), *pindex);
2167 LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
2168 pindex->GetBlockHash().ToString(), pfrom.GetId());
2169 }
2170 if (vGetData.size() > 1) {
2171 LogPrint(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n",
2172 pindexLast->GetBlockHash().ToString(), pindexLast->nHeight);
2173 }
2174 if (vGetData.size() > 0) {
2175 if (!m_ignore_incoming_txs &&
2176 nodestate->fSupportsDesiredCmpctVersion &&
2177 vGetData.size() == 1 &&
2178 mapBlocksInFlight.size() == 1 &&
2179 pindexLast->pprev->IsValid(BLOCK_VALID_CHAIN)) {
2180 // In any case, we want to download using a compact block, not a regular one
2181 vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
2182 }
2183 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vGetData));
2184 }
2185 }
2186 }
2187 // If we're in IBD, we want outbound peers that will serve us a useful
2188 // chain. Disconnect peers that are on chains with insufficient work.
2189 if (m_chainman.ActiveChainstate().IsInitialBlockDownload() && nCount != MAX_HEADERS_RESULTS) {
2190 // When nCount < MAX_HEADERS_RESULTS, we know we have no more
2191 // headers to fetch from this peer.
2192 if (nodestate->pindexBestKnownBlock && nodestate->pindexBestKnownBlock->nChainWork < nMinimumChainWork) {
2193 // This peer has too little work on their headers chain to help
2194 // us sync -- disconnect if it is an outbound disconnection
2195 // candidate.
2196 // Note: We compare their tip to nMinimumChainWork (rather than
2197 // m_chainman.ActiveChain().Tip()) because we won't start block download
2198 // until we have a headers chain that has at least
2199 // nMinimumChainWork, even if a peer has a chain past our tip,
2200 // as an anti-DoS measure.
2201 if (pfrom.IsOutboundOrBlockRelayConn()) {
2202 LogPrintf("Disconnecting outbound peer %d -- headers chain has insufficient work\n", pfrom.GetId());
2203 pfrom.fDisconnect = true;
2204 }
2205 }
2206 }
2207
2208 // If this is an outbound full-relay peer, check to see if we should protect
2209 // it from the bad/lagging chain logic.
2210 // Note that outbound block-relay peers are excluded from this protection, and
2211 // thus always subject to eviction under the bad/lagging chain logic.
2212 // See ChainSyncTimeoutState.
2213 if (!pfrom.fDisconnect && pfrom.IsFullOutboundConn() && nodestate->pindexBestKnownBlock != nullptr) {
2214 if (m_outbound_peers_with_protect_from_disconnect < MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT && nodestate->pindexBestKnownBlock->nChainWork >= m_chainman.ActiveChain().Tip()->nChainWork && !nodestate->m_chain_sync.m_protect) {
2215 LogPrint(BCLog::NET, "Protecting outbound peer=%d from eviction\n", pfrom.GetId());
2216 nodestate->m_chain_sync.m_protect = true;
2217 ++m_outbound_peers_with_protect_from_disconnect;
2218 }
2219 }
2220 }
2221
2222 return;
2223}
2224
2233void PeerManagerImpl::ProcessOrphanTx(std::set<uint256>& orphan_work_set)
2234{
2237
2238 while (!orphan_work_set.empty()) {
2239 const uint256 orphanHash = *orphan_work_set.begin();
2240 orphan_work_set.erase(orphan_work_set.begin());
2241
2242 const auto [porphanTx, from_peer] = m_orphanage.GetTx(orphanHash);
2243 if (porphanTx == nullptr) continue;
2244
2245 const MempoolAcceptResult result = AcceptToMemoryPool(m_chainman.ActiveChainstate(), m_mempool, porphanTx, false /* bypass_limits */);
2246 const TxValidationState& state = result.m_state;
2247
2249 LogPrint(BCLog::MEMPOOL, " accepted orphan tx %s\n", orphanHash.ToString());
2250 _RelayTransaction(orphanHash, porphanTx->GetWitnessHash());
2251 m_orphanage.AddChildrenToWorkSet(*porphanTx, orphan_work_set);
2252 m_orphanage.EraseTx(orphanHash);
2253 for (const CTransactionRef& removedTx : result.m_replaced_transactions.value()) {
2254 AddToCompactExtraTransactions(removedTx);
2255 }
2256 break;
2257 } else if (state.GetResult() != TxValidationResult::TX_MISSING_INPUTS) {
2258 if (state.IsInvalid()) {
2259 LogPrint(BCLog::MEMPOOL, " invalid orphan tx %s from peer=%d. %s\n",
2260 orphanHash.ToString(),
2261 from_peer,
2262 state.ToString());
2263 // Maybe punish peer that gave us an invalid orphan tx
2264 MaybePunishNodeForTx(from_peer, state);
2265 }
2266 // Has inputs but not accepted to mempool
2267 // Probably non-standard or insufficient fee
2268 LogPrint(BCLog::MEMPOOL, " removed orphan tx %s\n", orphanHash.ToString());
2270 // We can add the wtxid of this transaction to our reject filter.
2271 // Do not add txids of witness transactions or witness-stripped
2272 // transactions to the filter, as they can have been malleated;
2273 // adding such txids to the reject filter would potentially
2274 // interfere with relay of valid transactions from peers that
2275 // do not support wtxid-based relay. See
2276 // https://github.com/bitcoin/bitcoin/issues/8279 for details.
2277 // We can remove this restriction (and always add wtxids to
2278 // the filter even for witness stripped transactions) once
2279 // wtxid-based relay is broadly deployed.
2280 // See also comments in https://github.com/bitcoin/bitcoin/pull/18044#discussion_r443419034
2281 // for concerns around weakening security of unupgraded nodes
2282 // if we start doing this too early.
2283 m_recent_rejects.insert(porphanTx->GetWitnessHash());
2284 // If the transaction failed for TX_INPUTS_NOT_STANDARD,
2285 // then we know that the witness was irrelevant to the policy
2286 // failure, since this check depends only on the txid
2287 // (the scriptPubKey being spent is covered by the txid).
2288 // Add the txid to the reject filter to prevent repeated
2289 // processing of this transaction in the event that child
2290 // transactions are later received (resulting in
2291 // parent-fetching by txid via the orphan-handling logic).
2292 if (state.GetResult() == TxValidationResult::TX_INPUTS_NOT_STANDARD && porphanTx->GetWitnessHash() != porphanTx->GetHash()) {
2293 // We only add the txid if it differs from the wtxid, to
2294 // avoid wasting entries in the rolling bloom filter.
2295 m_recent_rejects.insert(porphanTx->GetHash());
2296 }
2297 }
2298 m_orphanage.EraseTx(orphanHash);
2299 break;
2300 }
2301 }
2302 CChainState& active_chainstate = m_chainman.ActiveChainstate();
2303 m_mempool.check(active_chainstate.CoinsTip(), active_chainstate.m_chain.Height() + 1);
2304}
2305
2306bool PeerManagerImpl::PrepareBlockFilterRequest(CNode& peer,
2307 BlockFilterType filter_type, uint32_t start_height,
2308 const uint256& stop_hash, uint32_t max_height_diff,
2309 const CBlockIndex*& stop_index,
2310 BlockFilterIndex*& filter_index)
2311{
2312 const bool supported_filter_type =
2313 (filter_type == BlockFilterType::BASIC &&
2315 if (!supported_filter_type) {
2316 LogPrint(BCLog::NET, "peer %d requested unsupported block filter type: %d\n",
2317 peer.GetId(), static_cast<uint8_t>(filter_type));
2318 peer.fDisconnect = true;
2319 return false;
2320 }
2321
2322 {
2323 LOCK(cs_main);
2324 stop_index = m_chainman.m_blockman.LookupBlockIndex(stop_hash);
2325
2326 // Check that the stop block exists and the peer would be allowed to fetch it.
2327 if (!stop_index || !BlockRequestAllowed(stop_index)) {
2328 LogPrint(BCLog::NET, "peer %d requested invalid block hash: %s\n",
2329 peer.GetId(), stop_hash.ToString());
2330 peer.fDisconnect = true;
2331 return false;
2332 }
2333 }
2334
2335 uint32_t stop_height = stop_index->nHeight;
2336 if (start_height > stop_height) {
2337 LogPrint(BCLog::NET, "peer %d sent invalid getcfilters/getcfheaders with " /* Continued */
2338 "start height %d and stop height %d\n",
2339 peer.GetId(), start_height, stop_height);
2340 peer.fDisconnect = true;
2341 return false;
2342 }
2343 if (stop_height - start_height >= max_height_diff) {
2344 LogPrint(BCLog::NET, "peer %d requested too many cfilters/cfheaders: %d / %d\n",
2345 peer.GetId(), stop_height - start_height + 1, max_height_diff);
2346 peer.fDisconnect = true;
2347 return false;
2348 }
2349
2350 filter_index = GetBlockFilterIndex(filter_type);
2351 if (!filter_index) {
2352 LogPrint(BCLog::NET, "Filter index for supported type %s not found\n", BlockFilterTypeName(filter_type));
2353 return false;
2354 }
2355
2356 return true;
2357}
2358
2359void PeerManagerImpl::ProcessGetCFilters(CNode& peer, CDataStream& vRecv)
2360{
2361 uint8_t filter_type_ser;
2362 uint32_t start_height;
2363 uint256 stop_hash;
2364
2365 vRecv >> filter_type_ser >> start_height >> stop_hash;
2366
2367 const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
2368
2369 const CBlockIndex* stop_index;
2370 BlockFilterIndex* filter_index;
2371 if (!PrepareBlockFilterRequest(peer, filter_type, start_height, stop_hash,
2372 MAX_GETCFILTERS_SIZE, stop_index, filter_index)) {
2373 return;
2374 }
2375
2376 std::vector<BlockFilter> filters;
2377 if (!filter_index->LookupFilterRange(start_height, stop_index, filters)) {
2378 LogPrint(BCLog::NET, "Failed to find block filter in index: filter_type=%s, start_height=%d, stop_hash=%s\n",
2379 BlockFilterTypeName(filter_type), start_height, stop_hash.ToString());
2380 return;
2381 }
2382
2383 for (const auto& filter : filters) {
2385 .Make(NetMsgType::CFILTER, filter);
2386 m_connman.PushMessage(&peer, std::move(msg));
2387 }
2388}
2389
2390void PeerManagerImpl::ProcessGetCFHeaders(CNode& peer, CDataStream& vRecv)
2391{
2392 uint8_t filter_type_ser;
2393 uint32_t start_height;
2394 uint256 stop_hash;
2395
2396 vRecv >> filter_type_ser >> start_height >> stop_hash;
2397
2398 const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
2399
2400 const CBlockIndex* stop_index;
2401 BlockFilterIndex* filter_index;
2402 if (!PrepareBlockFilterRequest(peer, filter_type, start_height, stop_hash,
2403 MAX_GETCFHEADERS_SIZE, stop_index, filter_index)) {
2404 return;
2405 }
2406
2407 uint256 prev_header;
2408 if (start_height > 0) {
2409 const CBlockIndex* const prev_block =
2410 stop_index->GetAncestor(static_cast<int>(start_height - 1));
2411 if (!filter_index->LookupFilterHeader(prev_block, prev_header)) {
2412 LogPrint(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n",
2413 BlockFilterTypeName(filter_type), prev_block->GetBlockHash().ToString());
2414 return;
2415 }
2416 }
2417
2418 std::vector<uint256> filter_hashes;
2419 if (!filter_index->LookupFilterHashRange(start_height, stop_index, filter_hashes)) {
2420 LogPrint(BCLog::NET, "Failed to find block filter hashes in index: filter_type=%s, start_height=%d, stop_hash=%s\n",
2421 BlockFilterTypeName(filter_type), start_height, stop_hash.ToString());
2422 return;
2423 }
2424
2427 filter_type_ser,
2428 stop_index->GetBlockHash(),
2429 prev_header,
2430 filter_hashes);
2431 m_connman.PushMessage(&peer, std::move(msg));
2432}
2433
2434void PeerManagerImpl::ProcessGetCFCheckPt(CNode& peer, CDataStream& vRecv)
2435{
2436 uint8_t filter_type_ser;
2437 uint256 stop_hash;
2438
2439 vRecv >> filter_type_ser >> stop_hash;
2440
2441 const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
2442
2443 const CBlockIndex* stop_index;
2444 BlockFilterIndex* filter_index;
2445 if (!PrepareBlockFilterRequest(peer, filter_type, /*start_height=*/0, stop_hash,
2446 /*max_height_diff=*/std::numeric_limits<uint32_t>::max(),
2447 stop_index, filter_index)) {
2448 return;
2449 }
2450
2451 std::vector<uint256> headers(stop_index->nHeight / CFCHECKPT_INTERVAL);
2452
2453 // Populate headers.
2454 const CBlockIndex* block_index = stop_index;
2455 for (int i = headers.size() - 1; i >= 0; i--) {
2456 int height = (i + 1) * CFCHECKPT_INTERVAL;
2457 block_index = block_index->GetAncestor(height);
2458
2459 if (!filter_index->LookupFilterHeader(block_index, headers[i])) {
2460 LogPrint(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n",
2461 BlockFilterTypeName(filter_type), block_index->GetBlockHash().ToString());
2462 return;
2463 }
2464 }
2465
2468 filter_type_ser,
2469 stop_index->GetBlockHash(),
2470 headers);
2471 m_connman.PushMessage(&peer, std::move(msg));
2472}
2473
2474void PeerManagerImpl::ProcessBlock(CNode& node, const std::shared_ptr<const CBlock>& block, bool force_processing)
2475{
2476 bool new_block{false};
2477 m_chainman.ProcessNewBlock(m_chainparams, block, force_processing, &new_block);
2478 if (new_block) {
2479 node.nLastBlockTime = GetTime();
2480 } else {
2481 LOCK(cs_main);
2482 mapBlockSource.erase(block->GetHash());
2483 }
2484}
2485
2486void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type, CDataStream& vRecv,
2487 const std::chrono::microseconds time_received,
2488 const std::atomic<bool>& interruptMsgProc)
2489{
2490 LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(msg_type), vRecv.size(), pfrom.GetId());
2491
2492 PeerRef peer = GetPeerRef(pfrom.GetId());
2493 if (peer == nullptr) return;
2494
2495 if (msg_type == NetMsgType::VERSION) {
2496 if (pfrom.nVersion != 0) {
2497 LogPrint(BCLog::NET, "redundant version message from peer=%d\n", pfrom.GetId());
2498 return;
2499 }
2500
2501 int64_t nTime;
2502 CService addrMe;
2503 uint64_t nNonce = 1;
2504 ServiceFlags nServices;
2505 int nVersion;
2506 std::string cleanSubVer;
2507 int starting_height = -1;
2508 bool fRelay = true;
2509
2510 vRecv >> nVersion >> Using<CustomUintFormatter<8>>(nServices) >> nTime;
2511 if (nTime < 0) {
2512 nTime = 0;
2513 }
2514 vRecv.ignore(8); // Ignore the addrMe service bits sent by the peer
2515 vRecv >> addrMe;
2516 if (!pfrom.IsInboundConn())
2517 {
2518 m_addrman.SetServices(pfrom.addr, nServices);
2519 }
2520 if (pfrom.ExpectServicesFromConn() && !HasAllDesirableServiceFlags(nServices))
2521 {
2522 LogPrint(BCLog::NET, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom.GetId(), nServices, GetDesirableServiceFlags(nServices));
2523 pfrom.fDisconnect = true;
2524 return;
2525 }
2526
2527 if (nVersion < MIN_PEER_PROTO_VERSION) {
2528 // disconnect from peers older than this proto version
2529 LogPrint(BCLog::NET, "peer=%d using obsolete version %i; disconnecting\n", pfrom.GetId(), nVersion);
2530 pfrom.fDisconnect = true;
2531 return;
2532 }
2533
2534 if (!vRecv.empty()) {
2535 // The version message includes information about the sending node which we don't use:
2536 // - 8 bytes (service bits)
2537 // - 16 bytes (ipv6 address)
2538 // - 2 bytes (port)
2539 vRecv.ignore(26);
2540 vRecv >> nNonce;
2541 }
2542 if (!vRecv.empty()) {
2543 std::string strSubVer;
2544 vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
2545 cleanSubVer = SanitizeString(strSubVer);
2546 }
2547 if (!vRecv.empty()) {
2548 vRecv >> starting_height;
2549 }
2550 if (!vRecv.empty())
2551 vRecv >> fRelay;
2552 // Disconnect if we connected to ourself
2553 if (pfrom.IsInboundConn() && !m_connman.CheckIncomingNonce(nNonce))
2554 {
2555 LogPrintf("connected to self at %s, disconnecting\n", pfrom.addr.ToString());
2556 pfrom.fDisconnect = true;
2557 return;
2558 }
2559
2560 if (pfrom.IsInboundConn() && addrMe.IsRoutable())
2561 {
2562 SeenLocal(addrMe);
2563 }
2564
2565 // Inbound peers send us their version message when they connect.
2566 // We send our version message in response.
2567 if (pfrom.IsInboundConn()) PushNodeVersion(pfrom, GetAdjustedTime());
2568
2569 // Change version
2570 const int greatest_common_version = std::min(nVersion, PROTOCOL_VERSION);
2571 pfrom.SetCommonVersion(greatest_common_version);
2572 pfrom.nVersion = nVersion;
2573
2574 const CNetMsgMaker msg_maker(greatest_common_version);
2575
2576 if (greatest_common_version >= WTXID_RELAY_VERSION) {
2577 m_connman.PushMessage(&pfrom, msg_maker.Make(NetMsgType::WTXIDRELAY));
2578 }
2579
2580 // Signal ADDRv2 support (BIP155).
2581 if (greatest_common_version >= 70016) {
2582 // BIP155 defines addrv2 and sendaddrv2 for all protocol versions, but some
2583 // implementations reject messages they don't know. As a courtesy, don't send
2584 // it to nodes with a version before 70016, as no software is known to support
2585 // BIP155 that doesn't announce at least that protocol version number.
2586 m_connman.PushMessage(&pfrom, msg_maker.Make(NetMsgType::SENDADDRV2));
2587 }
2588
2589 m_connman.PushMessage(&pfrom, msg_maker.Make(NetMsgType::VERACK));
2590
2591 pfrom.nServices = nServices;
2592 pfrom.SetAddrLocal(addrMe);
2593 {
2594 LOCK(pfrom.cs_SubVer);
2595 pfrom.cleanSubVer = cleanSubVer;
2596 }
2597 peer->m_starting_height = starting_height;
2598
2599 // set nodes not relaying blocks and tx and not serving (parts) of the historical blockchain as "clients"
2600 pfrom.fClient = (!(nServices & NODE_NETWORK) && !(nServices & NODE_NETWORK_LIMITED));
2601
2602 // set nodes not capable of serving the complete blockchain history as "limited nodes"
2603 pfrom.m_limited_node = (!(nServices & NODE_NETWORK) && (nServices & NODE_NETWORK_LIMITED));
2604
2605 if (pfrom.m_tx_relay != nullptr) {
2606 LOCK(pfrom.m_tx_relay->cs_filter);
2607 pfrom.m_tx_relay->fRelayTxes = fRelay; // set to true after we get the first filter* message
2608 }
2609
2610 if((nServices & NODE_WITNESS))
2611 {
2612 LOCK(cs_main);
2613 State(pfrom.GetId())->fHaveWitness = true;
2614 }
2615
2616 // Potentially mark this peer as a preferred download peer.
2617 {
2618 LOCK(cs_main);
2619 UpdatePreferredDownload(pfrom, State(pfrom.GetId()));
2620 }
2621
2622 // Self advertisement & GETADDR logic
2623 if (!pfrom.IsInboundConn() && SetupAddressRelay(pfrom, *peer)) {
2624 // For outbound peers, we try to relay our address (so that other
2625 // nodes can try to find us more quickly, as we have no guarantee
2626 // that an outbound peer is even aware of how to reach us) and do a
2627 // one-time address fetch (to help populate/update our addrman). If
2628 // we're starting up for the first time, our addrman may be pretty
2629 // empty and no one will know who we are, so these mechanisms are
2630 // important to help us connect to the network.
2631 //
2632 // We skip this for block-relay-only peers. We want to avoid
2633 // potentially leaking addr information and we do not want to
2634 // indicate to the peer that we will participate in addr relay.
2635 if (fListen && !m_chainman.ActiveChainstate().IsInitialBlockDownload())
2636 {
2637 CAddress addr = GetLocalAddress(&pfrom.addr, pfrom.GetLocalServices());
2638 FastRandomContext insecure_rand;
2639 if (addr.IsRoutable())
2640 {
2641 LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
2642 PushAddress(*peer, addr, insecure_rand);
2643 } else if (IsPeerAddrLocalGood(&pfrom)) {
2644 addr.SetIP(addrMe);
2645 LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
2646 PushAddress(*peer, addr, insecure_rand);
2647 }
2648 }
2649
2650 // Get recent addresses
2651 m_connman.PushMessage(&pfrom, CNetMsgMaker(greatest_common_version).Make(NetMsgType::GETADDR));
2652 peer->m_getaddr_sent = true;
2653 // When requesting a getaddr, accept an additional MAX_ADDR_TO_SEND addresses in response
2654 // (bypassing the MAX_ADDR_PROCESSING_TOKEN_BUCKET limit).
2655 peer->m_addr_token_bucket += MAX_ADDR_TO_SEND;
2656 }
2657
2658 if (!pfrom.IsInboundConn()) {
2659 // For non-inbound connections, we update the addrman to record
2660 // connection success so that addrman will have an up-to-date
2661 // notion of which peers are online and available.
2662 //
2663 // While we strive to not leak information about block-relay-only
2664 // connections via the addrman, not moving an address to the tried
2665 // table is also potentially detrimental because new-table entries
2666 // are subject to eviction in the event of addrman collisions. We
2667 // mitigate the information-leak by never calling
2668 // AddrMan::Connected() on block-relay-only peers; see
2669 // FinalizeNode().
2670 //
2671 // This moves an address from New to Tried table in Addrman,
2672 // resolves tried-table collisions, etc.
2673 m_addrman.Good(pfrom.addr);
2674 }
2675
2676 std::string remoteAddr;
2677 if (fLogIPs)
2678 remoteAddr = ", peeraddr=" + pfrom.addr.ToString();
2679
2680 LogPrint(BCLog::NET, "receive version message: %s: version %d, blocks=%d, us=%s, txrelay=%d, peer=%d%s\n",
2681 cleanSubVer, pfrom.nVersion,
2682 peer->m_starting_height, addrMe.ToString(), fRelay, pfrom.GetId(),
2683 remoteAddr);
2684
2685 int64_t nTimeOffset = nTime - GetTime();
2686 pfrom.nTimeOffset = nTimeOffset;
2687 AddTimeData(pfrom.addr, nTimeOffset);
2688
2689 // If the peer is old enough to have the old alert system, send it the final alert.
2690 if (greatest_common_version <= 70012) {
2691 CDataStream finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK, PROTOCOL_VERSION);
2692 m_connman.PushMessage(&pfrom, CNetMsgMaker(greatest_common_version).Make("alert", finalAlert));
2693 }
2694
2695 // Feeler connections exist only to verify if address is online.
2696 if (pfrom.IsFeelerConn()) {
2697 LogPrint(BCLog::NET, "feeler connection completed peer=%d; disconnecting\n", pfrom.GetId());
2698 pfrom.fDisconnect = true;
2699 }
2700 return;
2701 }
2702
2703 if (pfrom.nVersion == 0) {
2704 // Must have a version message before anything else
2705 LogPrint(BCLog::NET, "non-version message before version handshake. Message \"%s\" from peer=%d\n", SanitizeString(msg_type), pfrom.GetId());
2706 return;
2707 }
2708
2709 // At this point, the outgoing message serialization version can't change.
2710 const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
2711
2712 if (msg_type == NetMsgType::VERACK) {
2713 if (pfrom.fSuccessfullyConnected) {
2714 LogPrint(BCLog::NET, "ignoring redundant verack message from peer=%d\n", pfrom.GetId());
2715 return;
2716 }
2717
2718 if (!pfrom.IsInboundConn()) {
2719 LogPrintf("New outbound peer connected: version: %d, blocks=%d, peer=%d%s (%s)\n",
2720 pfrom.nVersion.load(), peer->m_starting_height,
2721 pfrom.GetId(), (fLogIPs ? strprintf(", peeraddr=%s", pfrom.addr.ToString()) : ""),
2722 pfrom.ConnectionTypeAsString());
2723 }
2724
2725 if (pfrom.GetCommonVersion() >= SENDHEADERS_VERSION) {
2726 // Tell our peer we prefer to receive headers rather than inv's
2727 // We send this to non-NODE NETWORK peers as well, because even
2728 // non-NODE NETWORK peers can announce blocks (such as pruning
2729 // nodes)
2730 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::SENDHEADERS));
2731 }
2733 // Tell our peer we are willing to provide version 1 or 2 cmpctblocks
2734 // However, we do not request new block announcements using
2735 // cmpctblock messages.
2736 // We send this to non-NODE NETWORK peers as well, because
2737 // they may wish to request compact blocks from us
2738 bool fAnnounceUsingCMPCTBLOCK = false;
2739 uint64_t nCMPCTBLOCKVersion = 2;
2740 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
2741 nCMPCTBLOCKVersion = 1;
2742 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
2743 }
2744 pfrom.fSuccessfullyConnected = true;
2745 return;
2746 }
2747
2748 if (msg_type == NetMsgType::SENDHEADERS) {
2749 LOCK(cs_main);
2750 State(pfrom.GetId())->fPreferHeaders = true;
2751 return;
2752 }
2753
2754 if (msg_type == NetMsgType::SENDCMPCT) {
2755 bool fAnnounceUsingCMPCTBLOCK = false;
2756 uint64_t nCMPCTBLOCKVersion = 0;
2757 vRecv >> fAnnounceUsingCMPCTBLOCK >> nCMPCTBLOCKVersion;
2758 if (nCMPCTBLOCKVersion == 1 || nCMPCTBLOCKVersion == 2) {
2759 LOCK(cs_main);
2760 // fProvidesHeaderAndIDs is used to "lock in" version of compact blocks we send (fWantsCmpctWitness)
2761 if (!State(pfrom.GetId())->fProvidesHeaderAndIDs) {
2762 State(pfrom.GetId())->fProvidesHeaderAndIDs = true;
2763 State(pfrom.GetId())->fWantsCmpctWitness = nCMPCTBLOCKVersion == 2;
2764 }
2765 if (State(pfrom.GetId())->fWantsCmpctWitness == (nCMPCTBLOCKVersion == 2)) { // ignore later version announces
2766 State(pfrom.GetId())->fPreferHeaderAndIDs = fAnnounceUsingCMPCTBLOCK;
2767 // save whether peer selects us as BIP152 high-bandwidth peer
2768 // (receiving sendcmpct(1) signals high-bandwidth, sendcmpct(0) low-bandwidth)
2769 pfrom.m_bip152_highbandwidth_from = fAnnounceUsingCMPCTBLOCK;
2770 }
2771 if (!State(pfrom.GetId())->fSupportsDesiredCmpctVersion) {
2772 State(pfrom.GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 2);
2773 }
2774 }
2775 return;
2776 }
2777
2778 // BIP339 defines feature negotiation of wtxidrelay, which must happen between
2779 // VERSION and VERACK to avoid relay problems from switching after a connection is up.
2780 if (msg_type == NetMsgType::WTXIDRELAY) {
2781 if (pfrom.fSuccessfullyConnected) {
2782 // Disconnect peers that send a wtxidrelay message after VERACK.
2783 LogPrint(BCLog::NET, "wtxidrelay received after verack from peer=%d; disconnecting\n", pfrom.GetId());
2784 pfrom.fDisconnect = true;
2785 return;
2786 }
2787 if (pfrom.GetCommonVersion() >= WTXID_RELAY_VERSION) {
2788 LOCK(cs_main);
2789 if (!State(pfrom.GetId())->m_wtxid_relay) {
2790 State(pfrom.GetId())->m_wtxid_relay = true;
2791 m_wtxid_relay_peers++;
2792 } else {
2793 LogPrint(BCLog::NET, "ignoring duplicate wtxidrelay from peer=%d\n", pfrom.GetId());
2794 }
2795 } else {
2796 LogPrint(BCLog::NET, "ignoring wtxidrelay due to old common version=%d from peer=%d\n", pfrom.GetCommonVersion(), pfrom.GetId());
2797 }
2798 return;
2799 }
2800
2801 // BIP155 defines feature negotiation of addrv2 and sendaddrv2, which must happen
2802 // between VERSION and VERACK.
2803 if (msg_type == NetMsgType::SENDADDRV2) {
2804 if (pfrom.fSuccessfullyConnected) {
2805 // Disconnect peers that send a SENDADDRV2 message after VERACK.
2806 LogPrint(BCLog::NET, "sendaddrv2 received after verack from peer=%d; disconnecting\n", pfrom.GetId());
2807 pfrom.fDisconnect = true;
2808 return;
2809 }
2810 peer->m_wants_addrv2 = true;
2811 return;
2812 }
2813
2814 if (!pfrom.fSuccessfullyConnected) {
2815 LogPrint(BCLog::NET, "Unsupported message \"%s\" prior to verack from peer=%d\n", SanitizeString(msg_type), pfrom.GetId());
2816 return;
2817 }
2818
2819 if (msg_type == NetMsgType::ADDR || msg_type == NetMsgType::ADDRV2) {
2820 int stream_version = vRecv.GetVersion();
2821 if (msg_type == NetMsgType::ADDRV2) {
2822 // Add ADDRV2_FORMAT to the version so that the CNetAddr and CAddress
2823 // unserialize methods know that an address in v2 format is coming.
2824 stream_version |= ADDRV2_FORMAT;
2825 }
2826
2827 OverrideStream<CDataStream> s(&vRecv, vRecv.GetType(), stream_version);
2828 std::vector<CAddress> vAddr;
2829
2830 s >> vAddr;
2831
2832 if (!SetupAddressRelay(pfrom, *peer)) {
2833 LogPrint(BCLog::NET, "ignoring %s message from %s peer=%d\n", msg_type, pfrom.ConnectionTypeAsString(), pfrom.GetId());
2834 return;
2835 }
2836
2837 if (vAddr.size() > MAX_ADDR_TO_SEND)
2838 {
2839 Misbehaving(pfrom.GetId(), 20, strprintf("%s message size = %u", msg_type, vAddr.size()));
2840 return;
2841 }
2842
2843 // Store the new addresses
2844 std::vector<CAddress> vAddrOk;
2845 int64_t nNow = GetAdjustedTime();
2846 int64_t nSince = nNow - 10 * 60;
2847
2848 // Update/increment addr rate limiting bucket.
2849 const auto current_time = GetTime<std::chrono::microseconds>();
2850 if (peer->m_addr_token_bucket < MAX_ADDR_PROCESSING_TOKEN_BUCKET) {
2851 // Don't increment bucket if it's already full
2852 const auto time_diff = std::max(current_time - peer->m_addr_token_timestamp, 0us);
2853 const double increment = CountSecondsDouble(time_diff) * MAX_ADDR_RATE_PER_SECOND;
2854 peer->m_addr_token_bucket = std::min<double>(peer->m_addr_token_bucket + increment, MAX_ADDR_PROCESSING_TOKEN_BUCKET);
2855 }
2856 peer->m_addr_token_timestamp = current_time;
2857
2858 const bool rate_limited = !pfrom.HasPermission(NetPermissionFlags::Addr);
2859 uint64_t num_proc = 0;
2860 uint64_t num_rate_limit = 0;
2861 Shuffle(vAddr.begin(), vAddr.end(), FastRandomContext());
2862 for (CAddress& addr : vAddr)
2863 {
2864 if (interruptMsgProc)
2865 return;
2866
2867 // Apply rate limiting.
2868 if (peer->m_addr_token_bucket < 1.0) {
2869 if (rate_limited) {
2870 ++num_rate_limit;
2871 continue;
2872 }
2873 } else {
2874 peer->m_addr_token_bucket -= 1.0;
2875 }
2876 // We only bother storing full nodes, though this may include
2877 // things which we would not make an outbound connection to, in
2878 // part because we may make feeler connections to them.
2880 continue;
2881
2882 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2883 addr.nTime = nNow - 5 * 24 * 60 * 60;
2884 AddAddressKnown(*peer, addr);
2885 if (m_banman && (m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr))) {
2886 // Do not process banned/discouraged addresses beyond remembering we received them
2887 continue;
2888 }
2889 ++num_proc;
2890 bool fReachable = IsReachable(addr);
2891 if (addr.nTime > nSince && !peer->m_getaddr_sent && vAddr.size() <= 10 && addr.IsRoutable()) {
2892 // Relay to a limited number of other nodes
2893 RelayAddress(pfrom.GetId(), addr, fReachable);
2894 }
2895 // Do not store addresses outside our network
2896 if (fReachable)
2897 vAddrOk.push_back(addr);
2898 }
2899 peer->m_addr_processed += num_proc;
2900 peer->m_addr_rate_limited += num_rate_limit;
2901 LogPrint(BCLog::NET, "Received addr: %u addresses (%u processed, %u rate-limited) from peer=%d\n",
2902 vAddr.size(), num_proc, num_rate_limit, pfrom.GetId());
2903
2904 m_addrman.Add(vAddrOk, pfrom.addr, 2 * 60 * 60);
2905 if (vAddr.size() < 1000) peer->m_getaddr_sent = false;
2906
2907 // AddrFetch: Require multiple addresses to avoid disconnecting on self-announcements
2908 if (pfrom.IsAddrFetchConn() && vAddr.size() > 1) {
2909 LogPrint(BCLog::NET, "addrfetch connection completed peer=%d; disconnecting\n", pfrom.GetId());
2910 pfrom.fDisconnect = true;
2911 }
2912 return;
2913 }
2914
2915 if (msg_type == NetMsgType::INV) {
2916 std::vector<CInv> vInv;
2917 vRecv >> vInv;
2918 if (vInv.size() > MAX_INV_SZ)
2919 {
2920 Misbehaving(pfrom.GetId(), 20, strprintf("inv message size = %u", vInv.size()));
2921 return;
2922 }
2923
2924 // Reject tx INVs when the -blocksonly setting is enabled, or this is a
2925 // block-relay-only peer
2926 bool reject_tx_invs{m_ignore_incoming_txs || (pfrom.m_tx_relay == nullptr)};
2927
2928 // Allow peers with relay permission to send data other than blocks in blocks only mode
2930 reject_tx_invs = false;
2931 }
2932
2933 LOCK(cs_main);
2934
2935 const auto current_time = GetTime<std::chrono::microseconds>();
2936 uint256* best_block{nullptr};
2937
2938 for (CInv& inv : vInv) {
2939 if (interruptMsgProc) return;
2940
2941 // Ignore INVs that don't match wtxidrelay setting.
2942 // Note that orphan parent fetching always uses MSG_TX GETDATAs regardless of the wtxidrelay setting.
2943 // This is fine as no INV messages are involved in that process.
2944 if (State(pfrom.GetId())->m_wtxid_relay) {
2945 if (inv.IsMsgTx()) continue;
2946 } else {
2947 if (inv.IsMsgWtx()) continue;
2948 }
2949
2950 if (inv.IsMsgBlk()) {
2951 const bool fAlreadyHave = AlreadyHaveBlock(inv.hash);
2952 LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId());
2953
2954 UpdateBlockAvailability(pfrom.GetId(), inv.hash);
2955 if (!fAlreadyHave && !fImporting && !fReindex && !IsBlockRequested(inv.hash)) {
2956 // Headers-first is the primary method of announcement on
2957 // the network. If a node fell back to sending blocks by inv,
2958 // it's probably for a re-org. The final block hash
2959 // provided should be the highest, so send a getheaders and
2960 // then fetch the blocks we need to catch up.
2961 best_block = &inv.hash;
2962 }
2963 } else if (inv.IsGenTxMsg()) {
2964 if (reject_tx_invs) {
2965 LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol, disconnecting peer=%d\n", inv.hash.ToString(), pfrom.GetId());
2966 pfrom.fDisconnect = true;
2967 return;
2968 }
2969 const GenTxid gtxid = ToGenTxid(inv);
2970 const bool fAlreadyHave = AlreadyHaveTx(gtxid);
2971 LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId());
2972
2973 pfrom.AddKnownTx(inv.hash);
2974 if (!fAlreadyHave && !m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
2975 AddTxAnnouncement(pfrom, gtxid, current_time);
2976 }
2977 } else {
2978 LogPrint(BCLog::NET, "Unknown inv type \"%s\" received from peer=%d\n", inv.ToString(), pfrom.GetId());
2979 }
2980 }
2981
2982 if (best_block != nullptr) {
2983 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETHEADERS, m_chainman.ActiveChain().GetLocator(pindexBestHeader), *best_block));
2984 LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, best_block->ToString(), pfrom.GetId());
2985 }
2986
2987 return;
2988 }
2989
2990 if (msg_type == NetMsgType::GETDATA) {
2991 std::vector<CInv> vInv;
2992 vRecv >> vInv;
2993 if (vInv.size() > MAX_INV_SZ)
2994 {
2995 Misbehaving(pfrom.GetId(), 20, strprintf("getdata message size = %u", vInv.size()));
2996 return;
2997 }
2998
2999 LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom.GetId());
3000
3001 if (vInv.size() > 0) {
3002 LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom.GetId());
3003 }
3004
3005 {
3006 LOCK(peer->m_getdata_requests_mutex);
3007 peer->m_getdata_requests.insert(peer->m_getdata_requests.end(), vInv.begin(), vInv.end());
3008 ProcessGetData(pfrom, *peer, interruptMsgProc);
3009 }
3010
3011 return;
3012 }
3013
3014 if (msg_type == NetMsgType::GETBLOCKS) {
3015 CBlockLocator locator;
3016 uint256 hashStop;
3017 vRecv >> locator >> hashStop;
3018
3019 if (locator.vHave.size() > MAX_LOCATOR_SZ) {
3020 LogPrint(BCLog::NET, "getblocks locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.GetId());
3021 pfrom.fDisconnect = true;
3022 return;
3023 }
3024
3025 // We might have announced the currently-being-connected tip using a
3026 // compact block, which resulted in the peer sending a getblocks
3027 // request, which we would otherwise respond to without the new block.
3028 // To avoid this situation we simply verify that we are on our best
3029 // known chain now. This is super overkill, but we handle it better
3030 // for getheaders requests, and there are no known nodes which support
3031 // compact blocks but still use getblocks to request blocks.
3032 {
3033 std::shared_ptr<const CBlock> a_recent_block;
3034 {
3036 a_recent_block = most_recent_block;
3037 }
3039 if (!m_chainman.ActiveChainstate().ActivateBestChain(state, a_recent_block)) {
3040 LogPrint(BCLog::NET, "failed to activate chain (%s)\n", state.ToString());
3041 }
3042 }
3043
3044 LOCK(cs_main);
3045
3046 // Find the last block the caller has in the main chain
3047 const CBlockIndex* pindex = m_chainman.m_blockman.FindForkInGlobalIndex(m_chainman.ActiveChain(), locator);
3048
3049 // Send the rest of the chain
3050 if (pindex)
3051 pindex = m_chainman.ActiveChain().Next(pindex);
3052 int nLimit = 500;
3053 LogPrint(BCLog::NET, "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom.GetId());
3054 for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex))
3055 {
3056 if (pindex->GetBlockHash() == hashStop)
3057 {
3058 LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3059 break;
3060 }
3061 // If pruning, don't inv blocks unless we have on disk and are likely to still have
3062 // for some reasonable time window (1 hour) that block relay might require.
3063 const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / m_chainparams.GetConsensus().nPowTargetSpacing;
3064 if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= m_chainman.ActiveChain().Tip()->nHeight - nPrunedBlocksLikelyToHave))
3065 {
3066 LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3067 break;
3068 }
3069 WITH_LOCK(peer->m_block_inv_mutex, peer->m_blocks_for_inv_relay.push_back(pindex->GetBlockHash()));
3070 if (--nLimit <= 0) {
3071 // When this block is requested, we'll send an inv that'll
3072 // trigger the peer to getblocks the next batch of inventory.
3073 LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3074 WITH_LOCK(peer->m_block_inv_mutex, {peer->m_continuation_block = pindex->GetBlockHash();});
3075 break;
3076 }
3077 }
3078 return;
3079 }
3080
3081 if (msg_type == NetMsgType::GETBLOCKTXN) {
3083 vRecv >> req;
3084
3085 std::shared_ptr<const CBlock> recent_block;
3086 {
3088 if (most_recent_block_hash == req.blockhash)
3089 recent_block = most_recent_block;
3090 // Unlock cs_most_recent_block to avoid cs_main lock inversion
3091 }
3092 if (recent_block) {
3093 SendBlockTransactions(pfrom, *recent_block, req);
3094 return;
3095 }
3096
3097 {
3098 LOCK(cs_main);
3099
3100 const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(req.blockhash);
3101 if (!pindex || !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3102 LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block we don't have\n", pfrom.GetId());
3103 return;
3104 }
3105
3106 if (pindex->nHeight >= m_chainman.ActiveChain().Height() - MAX_BLOCKTXN_DEPTH) {
3107 CBlock block;
3108 bool ret = ReadBlockFromDisk(block, pindex, m_chainparams.GetConsensus());
3109 assert(ret);
3110
3111 SendBlockTransactions(pfrom, block, req);
3112 return;
3113 }
3114 }
3115
3116 // If an older block is requested (should never happen in practice,
3117 // but can happen in tests) send a block response instead of a
3118 // blocktxn response. Sending a full block response instead of a
3119 // small blocktxn response is preferable in the case where a peer
3120 // might maliciously send lots of getblocktxn requests to trigger
3121 // expensive disk reads, because it will require the peer to
3122 // actually receive all the data read from disk over the network.
3123 LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep\n", pfrom.GetId(), MAX_BLOCKTXN_DEPTH);
3124 CInv inv;
3125 WITH_LOCK(cs_main, inv.type = State(pfrom.GetId())->fWantsCmpctWitness ? MSG_WITNESS_BLOCK : MSG_BLOCK);
3126 inv.hash = req.blockhash;
3127 WITH_LOCK(peer->m_getdata_requests_mutex, peer->m_getdata_requests.push_back(inv));
3128 // The message processing loop will go around again (without pausing) and we'll respond then
3129 return;
3130 }
3131
3132 if (msg_type == NetMsgType::GETHEADERS) {
3133 CBlockLocator locator;
3134 uint256 hashStop;
3135 vRecv >> locator >> hashStop;
3136
3137 if (locator.vHave.size() > MAX_LOCATOR_SZ) {
3138 LogPrint(BCLog::NET, "getheaders locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom.GetId());
3139 pfrom.fDisconnect = true;
3140 return;
3141 }
3142
3143 LOCK(cs_main);
3145 LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom.GetId());
3146 return;
3147 }
3148
3149 CNodeState *nodestate = State(pfrom.GetId());
3150 const CBlockIndex* pindex = nullptr;
3151 if (locator.IsNull())
3152 {
3153 // If locator is null, return the hashStop block
3154 pindex = m_chainman.m_blockman.LookupBlockIndex(hashStop);
3155 if (!pindex) {
3156 return;
3157 }
3158
3159 if (!BlockRequestAllowed(pindex)) {
3160 LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__, pfrom.GetId());
3161 return;
3162 }
3163 }
3164 else
3165 {
3166 // Find the last block the caller has in the main chain
3167 pindex = m_chainman.m_blockman.FindForkInGlobalIndex(m_chainman.ActiveChain(), locator);
3168 if (pindex)
3169 pindex = m_chainman.ActiveChain().Next(pindex);
3170 }
3171
3172 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
3173 std::vector<CBlock> vHeaders;
3174 int nLimit = MAX_HEADERS_RESULTS;
3175 LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom.GetId());
3176 for (; pindex; pindex = m_chainman.ActiveChain().Next(pindex))
3177 {
3178 vHeaders.push_back(pindex->GetBlockHeader());
3179 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3180 break;
3181 }
3182 // pindex can be nullptr either if we sent m_chainman.ActiveChain().Tip() OR
3183 // if our peer has m_chainman.ActiveChain().Tip() (and thus we are sending an empty
3184 // headers message). In both cases it's safe to update
3185 // pindexBestHeaderSent to be our tip.
3186 //
3187 // It is important that we simply reset the BestHeaderSent value here,
3188 // and not max(BestHeaderSent, newHeaderSent). We might have announced
3189 // the currently-being-connected tip using a compact block, which
3190 // resulted in the peer sending a headers request, which we respond to
3191 // without the new block. By resetting the BestHeaderSent, we ensure we
3192 // will re-announce the new block via headers (or compact blocks again)
3193 // in the SendMessages logic.
3194 nodestate->pindexBestHeaderSent = pindex ? pindex : m_chainman.ActiveChain().Tip();
3195 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
3196 return;
3197 }
3198
3199 if (msg_type == NetMsgType::TX) {
3200 // Stop processing the transaction early if
3201 // 1) We are in blocks only mode and peer has no relay permission
3202 // 2) This peer is a block-relay-only peer
3203 if ((m_ignore_incoming_txs && !pfrom.HasPermission(NetPermissionFlags::Relay)) || (pfrom.m_tx_relay == nullptr))
3204 {
3205 LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom.GetId());
3206 pfrom.fDisconnect = true;
3207 return;
3208 }
3209
3210 CTransactionRef ptx;
3211 vRecv >> ptx;
3212 const CTransaction& tx = *ptx;
3213
3214 const uint256& txid = ptx->GetHash();
3215 const uint256& wtxid = ptx->GetWitnessHash();
3216
3218
3219 CNodeState* nodestate = State(pfrom.GetId());
3220
3221 const uint256& hash = nodestate->m_wtxid_relay ? wtxid : txid;
3222 pfrom.AddKnownTx(hash);
3223 if (nodestate->m_wtxid_relay && txid != wtxid) {
3224 // Insert txid into filterInventoryKnown, even for
3225 // wtxidrelay peers. This prevents re-adding of
3226 // unconfirmed parents to the recently_announced
3227 // filter, when a child tx is requested. See
3228 // ProcessGetData().
3229 pfrom.AddKnownTx(txid);
3230 }
3231
3232 m_txrequest.ReceivedResponse(pfrom.GetId(), txid);
3233 if (tx.HasWitness()) m_txrequest.ReceivedResponse(pfrom.GetId(), wtxid);
3234
3235 // We do the AlreadyHaveTx() check using wtxid, rather than txid - in the
3236 // absence of witness malleation, this is strictly better, because the
3237 // recent rejects filter may contain the wtxid but rarely contains
3238 // the txid of a segwit transaction that has been rejected.
3239 // In the presence of witness malleation, it's possible that by only
3240 // doing the check with wtxid, we could overlook a transaction which
3241 // was confirmed with a different witness, or exists in our mempool
3242 // with a different witness, but this has limited downside:
3243 // mempool validation does its own lookup of whether we have the txid
3244 // already; and an adversary can already relay us old transactions
3245 // (older than our recency filter) if trying to DoS us, without any need
3246 // for witness malleation.
3247 if (AlreadyHaveTx(GenTxid::Wtxid(wtxid))) {
3249 // Always relay transactions received from peers with forcerelay
3250 // permission, even if they were already in the mempool, allowing
3251 // the node to function as a gateway for nodes hidden behind it.
3252 if (!m_mempool.exists(GenTxid::Txid(tx.GetHash()))) {
3253 LogPrintf("Not relaying non-mempool transaction %s from forcerelay peer=%d\n", tx.GetHash().ToString(), pfrom.GetId());
3254 } else {
3255 LogPrintf("Force relaying tx %s from peer=%d\n", tx.GetHash().ToString(), pfrom.GetId());
3256 _RelayTransaction(tx.GetHash(), tx.GetWitnessHash());
3257 }
3258 }
3259 return;
3260 }
3261
3262 const MempoolAcceptResult result = AcceptToMemoryPool(m_chainman.ActiveChainstate(), m_mempool, ptx, false /* bypass_limits */);
3263 const TxValidationState& state = result.m_state;
3264
3266 CChainState& active_chainstate = m_chainman.ActiveChainstate();
3267 m_mempool.check(active_chainstate.CoinsTip(), active_chainstate.m_chain.Height() + 1);
3268 // As this version of the transaction was acceptable, we can forget about any
3269 // requests for it.
3270 m_txrequest.ForgetTxHash(tx.GetHash());
3271 m_txrequest.ForgetTxHash(tx.GetWitnessHash());
3272 _RelayTransaction(tx.GetHash(), tx.GetWitnessHash());
3273 m_orphanage.AddChildrenToWorkSet(tx, peer->m_orphan_work_set);
3274
3275 pfrom.nLastTXTime = GetTime();
3276
3277 LogPrint(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
3278 pfrom.GetId(),
3279 tx.GetHash().ToString(),
3280 m_mempool.size(), m_mempool.DynamicMemoryUsage() / 1000);
3281
3282 for (const CTransactionRef& removedTx : result.m_replaced_transactions.value()) {
3283 AddToCompactExtraTransactions(removedTx);
3284 }
3285
3286 // Recursively process any orphan transactions that depended on this one
3287 ProcessOrphanTx(peer->m_orphan_work_set);
3288 }
3290 {
3291 bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected
3292
3293 // Deduplicate parent txids, so that we don't have to loop over
3294 // the same parent txid more than once down below.
3295 std::vector<uint256> unique_parents;
3296 unique_parents.reserve(tx.vin.size());
3297 for (const CTxIn& txin : tx.vin) {
3298 // We start with all parents, and then remove duplicates below.
3299 unique_parents.push_back(txin.prevout.hash);
3300 }
3301 std::sort(unique_parents.begin(), unique_parents.end());
3302 unique_parents.erase(std::unique(unique_parents.begin(), unique_parents.end()), unique_parents.end());
3303 for (const uint256& parent_txid : unique_parents) {
3304 if (m_recent_rejects.contains(parent_txid)) {
3305 fRejectedParents = true;
3306 break;
3307 }
3308 }
3309 if (!fRejectedParents) {
3310 const auto current_time = GetTime<std::chrono::microseconds>();
3311
3312 for (const uint256& parent_txid : unique_parents) {
3313 // Here, we only have the txid (and not wtxid) of the
3314 // inputs, so we only request in txid mode, even for
3315 // wtxidrelay peers.
3316 // Eventually we should replace this with an improved
3317 // protocol for getting all unconfirmed parents.
3318 const auto gtxid{GenTxid::Txid(parent_txid)};
3319 pfrom.AddKnownTx(parent_txid);
3320 if (!AlreadyHaveTx(gtxid)) AddTxAnnouncement(pfrom, gtxid, current_time);
3321 }
3322
3323 if (m_orphanage.AddTx(ptx, pfrom.GetId())) {
3324 AddToCompactExtraTransactions(ptx);
3325 }
3326
3327 // Once added to the orphan pool, a tx is considered AlreadyHave, and we shouldn't request it anymore.
3328 m_txrequest.ForgetTxHash(tx.GetHash());
3329 m_txrequest.ForgetTxHash(tx.GetWitnessHash());
3330
3331 // DoS prevention: do not allow m_orphanage to grow unbounded (see CVE-2012-3789)
3332 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, gArgs.GetIntArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
3333 unsigned int nEvicted = m_orphanage.LimitOrphans(nMaxOrphanTx);
3334 if (nEvicted > 0) {
3335 LogPrint(BCLog::MEMPOOL, "orphanage overflow, removed %u tx\n", nEvicted);
3336 }
3337 } else {
3338 LogPrint(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s\n",tx.GetHash().ToString());
3339 // We will continue to reject this tx since it has rejected
3340 // parents so avoid re-requesting it from other peers.
3341 // Here we add both the txid and the wtxid, as we know that
3342 // regardless of what witness is provided, we will not accept
3343 // this, so we don't need to allow for redownload of this txid
3344 // from any of our non-wtxidrelay peers.
3345 m_recent_rejects.insert(tx.GetHash());
3346 m_recent_rejects.insert(tx.GetWitnessHash());
3347 m_txrequest.ForgetTxHash(tx.GetHash());
3348 m_txrequest.ForgetTxHash(tx.GetWitnessHash());
3349 }
3350 } else {
3352 // We can add the wtxid of this transaction to our reject filter.
3353 // Do not add txids of witness transactions or witness-stripped
3354 // transactions to the filter, as they can have been malleated;
3355 // adding such txids to the reject filter would potentially
3356 // interfere with relay of valid transactions from peers that
3357 // do not support wtxid-based relay. See
3358 // https://github.com/bitcoin/bitcoin/issues/8279 for details.
3359 // We can remove this restriction (and always add wtxids to
3360 // the filter even for witness stripped transactions) once
3361 // wtxid-based relay is broadly deployed.
3362 // See also comments in https://github.com/bitcoin/bitcoin/pull/18044#discussion_r443419034
3363 // for concerns around weakening security of unupgraded nodes
3364 // if we start doing this too early.
3365 m_recent_rejects.insert(tx.GetWitnessHash());
3366 m_txrequest.ForgetTxHash(tx.GetWitnessHash());
3367 // If the transaction failed for TX_INPUTS_NOT_STANDARD,
3368 // then we know that the witness was irrelevant to the policy
3369 // failure, since this check depends only on the txid
3370 // (the scriptPubKey being spent is covered by the txid).
3371 // Add the txid to the reject filter to prevent repeated
3372 // processing of this transaction in the event that child
3373 // transactions are later received (resulting in
3374 // parent-fetching by txid via the orphan-handling logic).
3376 m_recent_rejects.insert(tx.GetHash());
3377 m_txrequest.ForgetTxHash(tx.GetHash());
3378 }
3379 if (RecursiveDynamicUsage(*ptx) < 100000) {
3380 AddToCompactExtraTransactions(ptx);
3381 }
3382 }
3383 }
3384
3385 // If a tx has been detected by m_recent_rejects, we will have reached
3386 // this point and the tx will have been ignored. Because we haven't run
3387 // the tx through AcceptToMemoryPool, we won't have computed a DoS
3388 // score for it or determined exactly why we consider it invalid.
3389 //
3390 // This means we won't penalize any peer subsequently relaying a DoSy
3391 // tx (even if we penalized the first peer who gave it to us) because
3392 // we have to account for m_recent_rejects showing false positives. In
3393 // other words, we shouldn't penalize a peer if we aren't *sure* they
3394 // submitted a DoSy tx.
3395 //
3396 // Note that m_recent_rejects doesn't just record DoSy or invalid
3397 // transactions, but any tx not accepted by the mempool, which may be
3398 // due to node policy (vs. consensus). So we can't blanket penalize a
3399 // peer simply for relaying a tx that our m_recent_rejects has caught,
3400 // regardless of false positives.
3401
3402 if (state.IsInvalid()) {
3403 LogPrint(BCLog::MEMPOOLREJ, "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(),
3404 pfrom.GetId(),
3405 state.ToString());
3406 MaybePunishNodeForTx(pfrom.GetId(), state);
3407 }
3408 return;
3409 }
3410
3411 if (msg_type == NetMsgType::CMPCTBLOCK)
3412 {
3413 // Ignore cmpctblock received while importing
3414 if (fImporting || fReindex) {
3415 LogPrint(BCLog::NET, "Unexpected cmpctblock message received from peer %d\n", pfrom.GetId());
3416 return;
3417 }
3418
3419 CBlockHeaderAndShortTxIDs cmpctblock;
3420 vRecv >> cmpctblock;
3421
3422 bool received_new_header = false;
3423
3424 {
3425 LOCK(cs_main);
3426
3427 if (!m_chainman.m_blockman.LookupBlockIndex(cmpctblock.header.hashPrevBlock)) {
3428 // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
3429 if (!m_chainman.ActiveChainstate().IsInitialBlockDownload())
3430 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETHEADERS, m_chainman.ActiveChain().GetLocator(pindexBestHeader), uint256()));
3431 return;
3432 }
3433
3434 if (!m_chainman.m_blockman.LookupBlockIndex(cmpctblock.header.GetHash())) {
3435 received_new_header = true;
3436 }
3437 }
3438
3439 const CBlockIndex *pindex = nullptr;
3441 if (!m_chainman.ProcessNewBlockHeaders({cmpctblock.header}, state, m_chainparams, &pindex)) {
3442 if (state.IsInvalid()) {
3443 MaybePunishNodeForBlock(pfrom.GetId(), state, /*via_compact_block*/ true, "invalid header via cmpctblock");
3444 return;
3445 }
3446 }
3447
3448 // When we succeed in decoding a block's txids from a cmpctblock
3449 // message we typically jump to the BLOCKTXN handling code, with a
3450 // dummy (empty) BLOCKTXN message, to re-use the logic there in
3451 // completing processing of the putative block (without cs_main).
3452 bool fProcessBLOCKTXN = false;
3454
3455 // If we end up treating this as a plain headers message, call that as well
3456 // without cs_main.
3457 bool fRevertToHeaderProcessing = false;
3458
3459 // Keep a CBlock for "optimistic" compactblock reconstructions (see
3460 // below)
3461 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3462 bool fBlockReconstructed = false;
3463
3464 {
3466 // If AcceptBlockHeader returned true, it set pindex
3467 assert(pindex);
3468 UpdateBlockAvailability(pfrom.GetId(), pindex->GetBlockHash());
3469
3470 CNodeState *nodestate = State(pfrom.GetId());
3471
3472 // If this was a new header with more work than our tip, update the
3473 // peer's last block announcement time
3474 if (received_new_header && pindex->nChainWork > m_chainman.ActiveChain().Tip()->nChainWork) {
3475 nodestate->m_last_block_announcement = GetTime();
3476 }
3477
3478 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator blockInFlightIt = mapBlocksInFlight.find(pindex->GetBlockHash());
3479 bool fAlreadyInFlight = blockInFlightIt != mapBlocksInFlight.end();
3480
3481 if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here
3482 return;
3483
3484 if (pindex->nChainWork <= m_chainman.ActiveChain().Tip()->nChainWork || // We know something better
3485 pindex->nTx != 0) { // We had this block at some point, but pruned it
3486 if (fAlreadyInFlight) {
3487 // We requested this block for some reason, but our mempool will probably be useless
3488 // so we just grab the block via normal getdata
3489 std::vector<CInv> vInv(1);
3490 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
3491 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
3492 }
3493 return;
3494 }
3495
3496 // If we're not close to tip yet, give up and let parallel block fetch work its magic
3497 if (!fAlreadyInFlight && !CanDirectFetch()) {
3498 return;
3499 }
3500
3501 if (DeploymentActiveAt(*pindex, m_chainparams.GetConsensus(), Consensus::DEPLOYMENT_SEGWIT) && !nodestate->fSupportsDesiredCmpctVersion) {
3502 // Don't bother trying to process compact blocks from v1 peers
3503 // after segwit activates.
3504 return;
3505 }
3506
3507 // We want to be a bit conservative just to be extra careful about DoS
3508 // possibilities in compact block processing...
3509 if (pindex->nHeight <= m_chainman.ActiveChain().Height() + 2) {
3510 if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
3511 (fAlreadyInFlight && blockInFlightIt->second.first == pfrom.GetId())) {
3512 std::list<QueuedBlock>::iterator* queuedBlockIt = nullptr;
3513 if (!BlockRequested(pfrom.GetId(), *pindex, &queuedBlockIt)) {
3514 if (!(*queuedBlockIt)->partialBlock)
3515 (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&m_mempool));
3516 else {
3517 // The block was already in flight using compact blocks from the same peer
3518 LogPrint(BCLog::NET, "Peer sent us compact block we were already syncing!\n");
3519 return;
3520 }
3521 }
3522
3523 PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock;
3524 ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact);
3525 if (status == READ_STATUS_INVALID) {
3526 RemoveBlockRequest(pindex->GetBlockHash()); // Reset in-flight state in case Misbehaving does not result in a disconnect
3527 Misbehaving(pfrom.GetId(), 100, "invalid compact block");
3528 return;
3529 } else if (status == READ_STATUS_FAILED) {
3530 // Duplicate txindexes, the block is now in-flight, so just request it
3531 std::vector<CInv> vInv(1);
3532 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
3533 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
3534 return;
3535 }
3536
3538 for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
3539 if (!partialBlock.IsTxAvailable(i))
3540 req.indexes.push_back(i);
3541 }
3542 if (req.indexes.empty()) {
3543 // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
3545 txn.blockhash = cmpctblock.header.GetHash();
3546 blockTxnMsg << txn;
3547 fProcessBLOCKTXN = true;
3548 } else {
3549 req.blockhash = pindex->GetBlockHash();
3550 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETBLOCKTXN, req));
3551 }
3552 } else {
3553 // This block is either already in flight from a different
3554 // peer, or this peer has too many blocks outstanding to
3555 // download from.
3556 // Optimistically try to reconstruct anyway since we might be
3557 // able to without any round trips.
3558 PartiallyDownloadedBlock tempBlock(&m_mempool);
3559 ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
3560 if (status != READ_STATUS_OK) {
3561 // TODO: don't ignore failures
3562 return;
3563 }
3564 std::vector<CTransactionRef> dummy;
3565 status = tempBlock.FillBlock(*pblock, dummy);
3566 if (status == READ_STATUS_OK) {
3567 fBlockReconstructed = true;
3568 }
3569 }
3570 } else {
3571 if (fAlreadyInFlight) {
3572 // We requested this block, but its far into the future, so our
3573 // mempool will probably be useless - request the block normally
3574 std::vector<CInv> vInv(1);
3575 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
3576 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
3577 return;
3578 } else {
3579 // If this was an announce-cmpctblock, we want the same treatment as a header message
3580 fRevertToHeaderProcessing = true;
3581 }
3582 }
3583 } // cs_main
3584
3585 if (fProcessBLOCKTXN) {
3586 return ProcessMessage(pfrom, NetMsgType::BLOCKTXN, blockTxnMsg, time_received, interruptMsgProc);
3587 }
3588
3589 if (fRevertToHeaderProcessing) {
3590 // Headers received from HB compact block peers are permitted to be
3591 // relayed before full validation (see BIP 152), so we don't want to disconnect
3592 // the peer if the header turns out to be for an invalid block.
3593 // Note that if a peer tries to build on an invalid chain, that
3594 // will be detected and the peer will be disconnected/discouraged.
3595 return ProcessHeadersMessage(pfrom, *peer, {cmpctblock.header}, /*via_compact_block=*/true);
3596 }
3597
3598 if (fBlockReconstructed) {
3599 // If we got here, we were able to optimistically reconstruct a
3600 // block that is in flight from some other peer.
3601 {
3602 LOCK(cs_main);
3603 mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom.GetId(), false));
3604 }
3605 // Setting force_processing to true means that we bypass some of
3606 // our anti-DoS protections in AcceptBlock, which filters
3607 // unrequested blocks that might be trying to waste our resources
3608 // (eg disk space). Because we only try to reconstruct blocks when
3609 // we're close to caught up (via the CanDirectFetch() requirement
3610 // above, combined with the behavior of not requesting blocks until
3611 // we have a chain with at least nMinimumChainWork), and we ignore
3612 // compact blocks with less work than our tip, it is safe to treat
3613 // reconstructed compact blocks as having been requested.
3614 ProcessBlock(pfrom, pblock, /*force_processing=*/true);
3615 LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid()
3616 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) {
3617 // Clear download state for this block, which is in
3618 // process from some other peer. We do this after calling
3619 // ProcessNewBlock so that a malleated cmpctblock announcement
3620 // can't be used to interfere with block relay.
3621 RemoveBlockRequest(pblock->GetHash());
3622 }
3623 }
3624 return;
3625 }
3626
3627 if (msg_type == NetMsgType::BLOCKTXN)
3628 {
3629 // Ignore blocktxn received while importing
3630 if (fImporting || fReindex) {
3631 LogPrint(BCLog::NET, "Unexpected blocktxn message received from peer %d\n", pfrom.GetId());
3632 return;
3633 }
3634
3635 BlockTransactions resp;
3636 vRecv >> resp;
3637
3638 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3639 bool fBlockRead = false;
3640 {
3641 LOCK(cs_main);
3642
3643 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator it = mapBlocksInFlight.find(resp.blockhash);
3644 if (it == mapBlocksInFlight.end() || !it->second.second->partialBlock ||
3645 it->second.first != pfrom.GetId()) {
3646 LogPrint(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom.GetId());
3647 return;
3648 }
3649
3650 PartiallyDownloadedBlock& partialBlock = *it->second.second->partialBlock;
3651 ReadStatus status = partialBlock.FillBlock(*pblock, resp.txn);
3652 if (status == READ_STATUS_INVALID) {
3653 RemoveBlockRequest(resp.blockhash); // Reset in-flight state in case Misbehaving does not result in a disconnect
3654 Misbehaving(pfrom.GetId(), 100, "invalid compact block/non-matching block transactions");
3655 return;
3656 } else if (status == READ_STATUS_FAILED) {
3657 // Might have collided, fall back to getdata now :(
3658 std::vector<CInv> invs;
3659 invs.push_back(CInv(MSG_BLOCK | GetFetchFlags(pfrom), resp.blockhash));
3660 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, invs));
3661 } else {
3662 // Block is either okay, or possibly we received
3663 // READ_STATUS_CHECKBLOCK_FAILED.
3664 // Note that CheckBlock can only fail for one of a few reasons:
3665 // 1. bad-proof-of-work (impossible here, because we've already
3666 // accepted the header)
3667 // 2. merkleroot doesn't match the transactions given (already
3668 // caught in FillBlock with READ_STATUS_FAILED, so
3669 // impossible here)
3670 // 3. the block is otherwise invalid (eg invalid coinbase,
3671 // block is too big, too many legacy sigops, etc).
3672 // So if CheckBlock failed, #3 is the only possibility.
3673 // Under BIP 152, we don't discourage the peer unless proof of work is
3674 // invalid (we don't require all the stateless checks to have
3675 // been run). This is handled below, so just treat this as
3676 // though the block was successfully read, and rely on the
3677 // handling in ProcessNewBlock to ensure the block index is
3678 // updated, etc.
3679 RemoveBlockRequest(resp.blockhash); // it is now an empty pointer
3680 fBlockRead = true;
3681 // mapBlockSource is used for potentially punishing peers and
3682 // updating which peers send us compact blocks, so the race
3683 // between here and cs_main in ProcessNewBlock is fine.
3684 // BIP 152 permits peers to relay compact blocks after validating
3685 // the header only; we should not punish peers if the block turns
3686 // out to be invalid.
3687 mapBlockSource.emplace(resp.blockhash, std::make_pair(pfrom.GetId(), false));
3688 }
3689 } // Don't hold cs_main when we call into ProcessNewBlock
3690 if (fBlockRead) {
3691 // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
3692 // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
3693 // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent
3694 // disk-space attacks), but this should be safe due to the
3695 // protections in the compact block handler -- see related comment
3696 // in compact block optimistic reconstruction handling.
3697 ProcessBlock(pfrom, pblock, /*force_processing=*/true);
3698 }
3699 return;
3700 }
3701
3702 if (msg_type == NetMsgType::HEADERS)
3703 {
3704 // Ignore headers received while importing
3705 if (fImporting || fReindex) {
3706 LogPrint(BCLog::NET, "Unexpected headers message received from peer %d\n", pfrom.GetId());
3707 return;
3708 }
3709
3710 std::vector<CBlockHeader> headers;
3711
3712 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
3713 unsigned int nCount = ReadCompactSize(vRecv);
3714 if (nCount > MAX_HEADERS_RESULTS) {
3715 Misbehaving(pfrom.GetId(), 20, strprintf("headers message size = %u", nCount));
3716 return;
3717 }
3718 headers.resize(nCount);
3719 for (unsigned int n = 0; n < nCount; n++) {
3720 vRecv >> headers[n];
3721 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
3722 }
3723
3724 return ProcessHeadersMessage(pfrom, *peer, headers, /*via_compact_block=*/false);
3725 }
3726
3727 if (msg_type == NetMsgType::BLOCK)
3728 {
3729 // Ignore block received while importing
3730 if (fImporting || fReindex) {
3731 LogPrint(BCLog::NET, "Unexpected block message received from peer %d\n", pfrom.GetId());
3732 return;
3733 }
3734
3735 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3736 vRecv >> *pblock;
3737
3738 LogPrint(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom.GetId());
3739
3740 bool forceProcessing = false;
3741 const uint256 hash(pblock->GetHash());
3742 {
3743 LOCK(cs_main);
3744 // Always process the block if we requested it, since we may
3745 // need it even when it's not a candidate for a new best tip.
3746 forceProcessing = IsBlockRequested(hash);
3747 RemoveBlockRequest(hash);
3748 // mapBlockSource is only used for punishing peers and setting
3749 // which peers send us compact blocks, so the race between here and
3750 // cs_main in ProcessNewBlock is fine.
3751 mapBlockSource.emplace(hash, std::make_pair(pfrom.GetId(), true));
3752 }
3753 ProcessBlock(pfrom, pblock, forceProcessing);
3754 return;
3755 }
3756
3757 if (msg_type == NetMsgType::GETADDR) {
3758 // This asymmetric behavior for inbound and outbound connections was introduced
3759 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
3760 // to users' AddrMan and later request them by sending getaddr messages.
3761 // Making nodes which are behind NAT and can only make outgoing connections ignore
3762 // the getaddr message mitigates the attack.
3763 if (!pfrom.IsInboundConn()) {
3764 LogPrint(BCLog::NET, "Ignoring \"getaddr\" from %s connection. peer=%d\n", pfrom.ConnectionTypeAsString(), pfrom.GetId());
3765 return;
3766 }
3767
3768 // Since this must be an inbound connection, SetupAddressRelay will
3769 // never fail.
3770 Assume(SetupAddressRelay(pfrom, *peer));
3771
3772 // Only send one GetAddr response per connection to reduce resource waste
3773 // and discourage addr stamping of INV announcements.
3774 if (peer->m_getaddr_recvd) {
3775 LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom.GetId());
3776 return;
3777 }
3778 peer->m_getaddr_recvd = true;
3779
3780 peer->m_addrs_to_send.clear();
3781 std::vector<CAddress> vAddr;
3783 vAddr = m_connman.GetAddresses(MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND, /* network */ std::nullopt);
3784 } else {
3785 vAddr = m_connman.GetAddresses(pfrom, MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND);
3786 }
3787 FastRandomContext insecure_rand;
3788 for (const CAddress &addr : vAddr) {
3789 PushAddress(*peer, addr, insecure_rand);
3790 }
3791 return;
3792 }
3793
3794 if (msg_type == NetMsgType::MEMPOOL) {
3796 {
3798 {
3799 LogPrint(BCLog::NET, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom.GetId());
3800 pfrom.fDisconnect = true;
3801 }
3802 return;
3803 }
3804
3805 if (m_connman.OutboundTargetReached(false) && !pfrom.HasPermission(NetPermissionFlags::Mempool))
3806 {
3808 {
3809 LogPrint(BCLog::NET, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom.GetId());
3810 pfrom.fDisconnect = true;
3811 }
3812 return;
3813 }
3814
3815 if (pfrom.m_tx_relay != nullptr) {
3816 LOCK(pfrom.m_tx_relay->cs_tx_inventory);
3817 pfrom.m_tx_relay->fSendMempool = true;
3818 }
3819 return;
3820 }
3821
3822 if (msg_type == NetMsgType::PING) {
3823 if (pfrom.GetCommonVersion() > BIP0031_VERSION) {
3824 uint64_t nonce = 0;
3825 vRecv >> nonce;
3826 // Echo the message back with the nonce. This allows for two useful features:
3827 //
3828 // 1) A remote node can quickly check if the connection is operational
3829 // 2) Remote nodes can measure the latency of the network thread. If this node
3830 // is overloaded it won't respond to pings quickly and the remote node can
3831 // avoid sending us more work, like chain download requests.
3832 //
3833 // The nonce stops the remote getting confused between different pings: without
3834 // it, if the remote node sends a ping once per second and this node takes 5
3835 // seconds to respond to each, the 5th ping the remote sends would appear to
3836 // return very quickly.
3837 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::PONG, nonce));
3838 }
3839 return;
3840 }
3841
3842 if (msg_type == NetMsgType::PONG) {
3843 const auto ping_end = time_received;
3844 uint64_t nonce = 0;
3845 size_t nAvail = vRecv.in_avail();
3846 bool bPingFinished = false;
3847 std::string sProblem;
3848
3849 if (nAvail >= sizeof(nonce)) {
3850 vRecv >> nonce;
3851
3852 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
3853 if (peer->m_ping_nonce_sent != 0) {
3854 if (nonce == peer->m_ping_nonce_sent) {
3855 // Matching pong received, this ping is no longer outstanding
3856 bPingFinished = true;
3857 const auto ping_time = ping_end - peer->m_ping_start.load();
3858 if (ping_time.count() >= 0) {
3859 // Let connman know about this successful ping-pong
3860 pfrom.PongReceived(ping_time);
3861 } else {
3862 // This should never happen
3863 sProblem = "Timing mishap";
3864 }
3865 } else {
3866 // Nonce mismatches are normal when pings are overlapping
3867 sProblem = "Nonce mismatch";
3868 if (nonce == 0) {
3869 // This is most likely a bug in another implementation somewhere; cancel this ping
3870 bPingFinished = true;
3871 sProblem = "Nonce zero";
3872 }
3873 }
3874 } else {
3875 sProblem = "Unsolicited pong without ping";
3876 }
3877 } else {
3878 // This is most likely a bug in another implementation somewhere; cancel this ping
3879 bPingFinished = true;
3880 sProblem = "Short payload";
3881 }
3882
3883 if (!(sProblem.empty())) {
3884 LogPrint(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
3885 pfrom.GetId(),
3886 sProblem,
3887 peer->m_ping_nonce_sent,
3888 nonce,
3889 nAvail);
3890 }
3891 if (bPingFinished) {
3892 peer->m_ping_nonce_sent = 0;
3893 }
3894 return;
3895 }
3896
3897 if (msg_type == NetMsgType::FILTERLOAD) {
3898 if (!(pfrom.GetLocalServices() & NODE_BLOOM)) {
3899 LogPrint(BCLog::NET, "filterload received despite not offering bloom services from peer=%d; disconnecting\n", pfrom.GetId());
3900 pfrom.fDisconnect = true;
3901 return;
3902 }
3903 CBloomFilter filter;
3904 vRecv >> filter;
3905
3906 if (!filter.IsWithinSizeConstraints())
3907 {
3908 // There is no excuse for sending a too-large filter
3909 Misbehaving(pfrom.GetId(), 100, "too-large bloom filter");
3910 }
3911 else if (pfrom.m_tx_relay != nullptr)
3912 {
3913 LOCK(pfrom.m_tx_relay->cs_filter);
3914 pfrom.m_tx_relay->pfilter.reset(new CBloomFilter(filter));
3915 pfrom.m_tx_relay->fRelayTxes = true;
3916 }
3917 return;
3918 }
3919
3920 if (msg_type == NetMsgType::FILTERADD) {
3921 if (!(pfrom.GetLocalServices() & NODE_BLOOM)) {
3922 LogPrint(BCLog::NET, "filteradd received despite not offering bloom services from peer=%d; disconnecting\n", pfrom.GetId());
3923 pfrom.fDisconnect = true;
3924 return;
3925 }
3926 std::vector<unsigned char> vData;
3927 vRecv >> vData;
3928
3929 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
3930 // and thus, the maximum size any matched object can have) in a filteradd message
3931 bool bad = false;
3932 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
3933 bad = true;
3934 } else if (pfrom.m_tx_relay != nullptr) {
3935 LOCK(pfrom.m_tx_relay->cs_filter);
3936 if (pfrom.m_tx_relay->pfilter) {
3937 pfrom.m_tx_relay->pfilter->insert(vData);
3938 } else {
3939 bad = true;
3940 }
3941 }
3942 if (bad) {
3943 Misbehaving(pfrom.GetId(), 100, "bad filteradd message");
3944 }
3945 return;
3946 }
3947
3948 if (msg_type == NetMsgType::FILTERCLEAR) {
3949 if (!(pfrom.GetLocalServices() & NODE_BLOOM)) {
3950 LogPrint(BCLog::NET, "filterclear received despite not offering bloom services from peer=%d; disconnecting\n", pfrom.GetId());
3951 pfrom.fDisconnect = true;
3952 return;
3953 }
3954 if (pfrom.m_tx_relay == nullptr) {
3955 return;
3956 }
3957 LOCK(pfrom.m_tx_relay->cs_filter);
3958 pfrom.m_tx_relay->pfilter = nullptr;
3959 pfrom.m_tx_relay->fRelayTxes = true;
3960 return;
3961 }
3962
3963 if (msg_type == NetMsgType::FEEFILTER) {
3964 CAmount newFeeFilter = 0;
3965 vRecv >> newFeeFilter;
3966 if (MoneyRange(newFeeFilter)) {
3967 if (pfrom.m_tx_relay != nullptr) {
3968 pfrom.m_tx_relay->minFeeFilter = newFeeFilter;
3969 }
3970 LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom.GetId());
3971 }
3972 return;
3973 }
3974
3975 if (msg_type == NetMsgType::GETCFILTERS) {
3976 ProcessGetCFilters(pfrom, vRecv);
3977 return;
3978 }
3979
3980 if (msg_type == NetMsgType::GETCFHEADERS) {
3981 ProcessGetCFHeaders(pfrom, vRecv);
3982 return;
3983 }
3984
3985 if (msg_type == NetMsgType::GETCFCHECKPT) {
3986 ProcessGetCFCheckPt(pfrom, vRecv);
3987 return;
3988 }
3989
3990 if (msg_type == NetMsgType::NOTFOUND) {
3991 std::vector<CInv> vInv;
3992 vRecv >> vInv;
3994 LOCK(::cs_main);
3995 for (CInv &inv : vInv) {
3996 if (inv.IsGenTxMsg()) {
3997 // If we receive a NOTFOUND message for a tx we requested, mark the announcement for it as
3998 // completed in TxRequestTracker.
3999 m_txrequest.ReceivedResponse(pfrom.GetId(), inv.hash);
4000 }
4001 }
4002 }
4003 return;
4004 }
4005
4006 // Ignore unknown commands for extensibility
4007 LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(msg_type), pfrom.GetId());
4008 return;
4009}
4010
4011bool PeerManagerImpl::MaybeDiscourageAndDisconnect(CNode& pnode, Peer& peer)
4012{
4013 {
4014 LOCK(peer.m_misbehavior_mutex);
4015
4016 // There's nothing to do if the m_should_discourage flag isn't set
4017 if (!peer.m_should_discourage) return false;
4018
4019 peer.m_should_discourage = false;
4020 } // peer.m_misbehavior_mutex
4021
4023 // We never disconnect or discourage peers for bad behavior if they have NetPermissionFlags::NoBan permission
4024 LogPrintf("Warning: not punishing noban peer %d!\n", peer.m_id);
4025 return false;
4026 }
4027
4028 if (pnode.IsManualConn()) {
4029 // We never disconnect or discourage manual peers for bad behavior
4030 LogPrintf("Warning: not punishing manually connected peer %d!\n", peer.m_id);
4031 return false;
4032 }
4033
4034 if (pnode.addr.IsLocal()) {
4035 // We disconnect local peers for bad behavior but don't discourage (since that would discourage
4036 // all peers on the same local address)
4037 LogPrint(BCLog::NET, "Warning: disconnecting but not discouraging %s peer %d!\n",
4038 pnode.m_inbound_onion ? "inbound onion" : "local", peer.m_id);
4039 pnode.fDisconnect = true;
4040 return true;
4041 }
4042
4043 // Normal case: Disconnect the peer and discourage all nodes sharing the address
4044 LogPrint(BCLog::NET, "Disconnecting and discouraging peer %d!\n", peer.m_id);
4045 if (m_banman) m_banman->Discourage(pnode.addr);
4046 m_connman.DisconnectNode(pnode.addr);
4047 return true;
4048}
4049
4050bool PeerManagerImpl::ProcessMessages(CNode* pfrom, std::atomic<bool>& interruptMsgProc)
4051{
4052 bool fMoreWork = false;
4053
4054 PeerRef peer = GetPeerRef(pfrom->GetId());
4055 if (peer == nullptr) return false;
4056
4057 {
4058 LOCK(peer->m_getdata_requests_mutex);
4059 if (!peer->m_getdata_requests.empty()) {
4060 ProcessGetData(*pfrom, *peer, interruptMsgProc);
4061 }
4062 }
4063
4064 {
4066 if (!peer->m_orphan_work_set.empty()) {
4067 ProcessOrphanTx(peer->m_orphan_work_set);
4068 }
4069 }
4070
4071 if (pfrom->fDisconnect)
4072 return false;
4073
4074 // this maintains the order of responses
4075 // and prevents m_getdata_requests to grow unbounded
4076 {
4077 LOCK(peer->m_getdata_requests_mutex);
4078 if (!peer->m_getdata_requests.empty()) return true;
4079 }
4080
4081 {
4083 if (!peer->m_orphan_work_set.empty()) return true;
4084 }
4085
4086 // Don't bother if send buffer is too full to respond anyway
4087 if (pfrom->fPauseSend) return false;
4088
4089 std::list<CNetMessage> msgs;
4090 {
4091 LOCK(pfrom->cs_vProcessMsg);
4092 if (pfrom->vProcessMsg.empty()) return false;
4093 // Just take one message
4094 msgs.splice(msgs.begin(), pfrom->vProcessMsg, pfrom->vProcessMsg.begin());
4095 pfrom->nProcessQueueSize -= msgs.front().m_raw_message_size;
4096 pfrom->fPauseRecv = pfrom->nProcessQueueSize > m_connman.GetReceiveFloodSize();
4097 fMoreWork = !pfrom->vProcessMsg.empty();
4098 }
4099 CNetMessage& msg(msgs.front());
4100
4101 TRACE6(net, inbound_message,
4102 pfrom->GetId(),
4103 pfrom->m_addr_name.c_str(),
4104 pfrom->ConnectionTypeAsString().c_str(),
4105 msg.m_command.c_str(),
4106 msg.m_recv.size(),
4107 msg.m_recv.data()
4108 );
4109
4110 if (gArgs.GetBoolArg("-capturemessages", false)) {
4111 CaptureMessage(pfrom->addr, msg.m_command, MakeUCharSpan(msg.m_recv), /* incoming */ true);
4112 }
4113
4114 msg.SetVersion(pfrom->GetCommonVersion());
4115 const std::string& msg_type = msg.m_command;
4116
4117 // Message size
4118 unsigned int nMessageSize = msg.m_message_size;
4119
4120 try {
4121 ProcessMessage(*pfrom, msg_type, msg.m_recv, msg.m_time, interruptMsgProc);
4122 if (interruptMsgProc) return false;
4123 {
4124 LOCK(peer->m_getdata_requests_mutex);
4125 if (!peer->m_getdata_requests.empty()) fMoreWork = true;
4126 }
4127 } catch (const std::exception& e) {
4128 LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' (%s) caught\n", __func__, SanitizeString(msg_type), nMessageSize, e.what(), typeid(e).name());
4129 } catch (...) {
4130 LogPrint(BCLog::NET, "%s(%s, %u bytes): Unknown exception caught\n", __func__, SanitizeString(msg_type), nMessageSize);
4131 }
4132
4133 return fMoreWork;
4134}
4135
4136void PeerManagerImpl::ConsiderEviction(CNode& pto, int64_t time_in_seconds)
4137{
4139
4140 CNodeState &state = *State(pto.GetId());
4141 const CNetMsgMaker msgMaker(pto.GetCommonVersion());
4142
4143 if (!state.m_chain_sync.m_protect && pto.IsOutboundOrBlockRelayConn() && state.fSyncStarted) {
4144 // This is an outbound peer subject to disconnection if they don't
4145 // announce a block with as much work as the current tip within
4146 // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if
4147 // their chain has more work than ours, we should sync to it,
4148 // unless it's invalid, in which case we should find that out and
4149 // disconnect from them elsewhere).
4150 if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= m_chainman.ActiveChain().Tip()->nChainWork) {
4151 if (state.m_chain_sync.m_timeout != 0) {
4152 state.m_chain_sync.m_timeout = 0;
4153 state.m_chain_sync.m_work_header = nullptr;
4154 state.m_chain_sync.m_sent_getheaders = false;
4155 }
4156 } else if (state.m_chain_sync.m_timeout == 0 || (state.m_chain_sync.m_work_header != nullptr && state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= state.m_chain_sync.m_work_header->nChainWork)) {
4157 // Our best block known by this peer is behind our tip, and we're either noticing
4158 // that for the first time, OR this peer was able to catch up to some earlier point
4159 // where we checked against our tip.
4160 // Either way, set a new timeout based on current tip.
4161 state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT;
4162 state.m_chain_sync.m_work_header = m_chainman.ActiveChain().Tip();
4163 state.m_chain_sync.m_sent_getheaders = false;
4164 } else if (state.m_chain_sync.m_timeout > 0 && time_in_seconds > state.m_chain_sync.m_timeout) {
4165 // No evidence yet that our peer has synced to a chain with work equal to that
4166 // of our tip, when we first detected it was behind. Send a single getheaders
4167 // message to give the peer a chance to update us.
4168 if (state.m_chain_sync.m_sent_getheaders) {
4169 // They've run out of time to catch up!
4170 LogPrintf("Disconnecting outbound peer %d for old chain, best known block = %s\n", pto.GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>");
4171 pto.fDisconnect = true;
4172 } else {
4173 assert(state.m_chain_sync.m_work_header);
4174 LogPrint(BCLog::NET, "sending getheaders to outbound peer=%d to verify chain work (current best known block:%s, benchmark blockhash: %s)\n", pto.GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>", state.m_chain_sync.m_work_header->GetBlockHash().ToString());
4175 m_connman.PushMessage(&pto, msgMaker.Make(NetMsgType::GETHEADERS, m_chainman.ActiveChain().GetLocator(state.m_chain_sync.m_work_header->pprev), uint256()));
4176 state.m_chain_sync.m_sent_getheaders = true;
4177 constexpr int64_t HEADERS_RESPONSE_TIME = 120; // 2 minutes
4178 // Bump the timeout to allow a response, which could clear the timeout
4179 // (if the response shows the peer has synced), reset the timeout (if
4180 // the peer syncs to the required work but not to our tip), or result
4181 // in disconnect (if we advance to the timeout and pindexBestKnownBlock
4182 // has not sufficiently progressed)
4183 state.m_chain_sync.m_timeout = time_in_seconds + HEADERS_RESPONSE_TIME;
4184 }
4185 }
4186 }
4187}
4188
4189void PeerManagerImpl::EvictExtraOutboundPeers(int64_t time_in_seconds)
4190{
4191 // If we have any extra block-relay-only peers, disconnect the youngest unless
4192 // it's given us a block -- in which case, compare with the second-youngest, and
4193 // out of those two, disconnect the peer who least recently gave us a block.
4194 // The youngest block-relay-only peer would be the extra peer we connected
4195 // to temporarily in order to sync our tip; see net.cpp.
4196 // Note that we use higher nodeid as a measure for most recent connection.
4197 if (m_connman.GetExtraBlockRelayCount() > 0) {
4198 std::pair<NodeId, int64_t> youngest_peer{-1, 0}, next_youngest_peer{-1, 0};
4199
4200 m_connman.ForEachNode([&](CNode* pnode) {
4201 if (!pnode->IsBlockOnlyConn() || pnode->fDisconnect) return;
4202 if (pnode->GetId() > youngest_peer.first) {
4203 next_youngest_peer = youngest_peer;
4204 youngest_peer.first = pnode->GetId();
4205 youngest_peer.second = pnode->nLastBlockTime;
4206 }
4207 });
4208 NodeId to_disconnect = youngest_peer.first;
4209 if (youngest_peer.second > next_youngest_peer.second) {
4210 // Our newest block-relay-only peer gave us a block more recently;
4211 // disconnect our second youngest.
4212 to_disconnect = next_youngest_peer.first;
4213 }
4214 m_connman.ForNode(to_disconnect, [&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
4216 // Make sure we're not getting a block right now, and that
4217 // we've been connected long enough for this eviction to happen
4218 // at all.
4219 // Note that we only request blocks from a peer if we learn of a
4220 // valid headers chain with at least as much work as our tip.
4221 CNodeState *node_state = State(pnode->GetId());
4222 if (node_state == nullptr ||
4223 (time_in_seconds - pnode->nTimeConnected >= MINIMUM_CONNECT_TIME && node_state->nBlocksInFlight == 0)) {
4224 pnode->fDisconnect = true;
4225 LogPrint(BCLog::NET, "disconnecting extra block-relay-only peer=%d (last block received at time %d)\n", pnode->GetId(), pnode->nLastBlockTime);
4226 return true;
4227 } else {
4228 LogPrint(BCLog::NET, "keeping block-relay-only peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n",
4229 pnode->GetId(), pnode->nTimeConnected, node_state->nBlocksInFlight);
4230 }
4231 return false;
4232 });
4233 }
4234
4235 // Check whether we have too many outbound-full-relay peers
4236 if (m_connman.GetExtraFullOutboundCount() > 0) {
4237 // If we have more outbound-full-relay peers than we target, disconnect one.
4238 // Pick the outbound-full-relay peer that least recently announced
4239 // us a new block, with ties broken by choosing the more recent
4240 // connection (higher node id)
4241 NodeId worst_peer = -1;
4242 int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max();
4243
4244 m_connman.ForEachNode([&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
4246
4247 // Only consider outbound-full-relay peers that are not already
4248 // marked for disconnection
4249 if (!pnode->IsFullOutboundConn() || pnode->fDisconnect) return;
4250 CNodeState *state = State(pnode->GetId());
4251 if (state == nullptr) return; // shouldn't be possible, but just in case
4252 // Don't evict our protected peers
4253 if (state->m_chain_sync.m_protect) return;
4254 if (state->m_last_block_announcement < oldest_block_announcement || (state->m_last_block_announcement == oldest_block_announcement && pnode->GetId() > worst_peer)) {
4255 worst_peer = pnode->GetId();
4256 oldest_block_announcement = state->m_last_block_announcement;
4257 }
4258 });
4259 if (worst_peer != -1) {
4260 bool disconnected = m_connman.ForNode(worst_peer, [&](CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
4262
4263 // Only disconnect a peer that has been connected to us for
4264 // some reasonable fraction of our check-frequency, to give
4265 // it time for new information to have arrived.
4266 // Also don't disconnect any peer we're trying to download a
4267 // block from.
4268 CNodeState &state = *State(pnode->GetId());
4269 if (time_in_seconds - pnode->nTimeConnected > MINIMUM_CONNECT_TIME && state.nBlocksInFlight == 0) {
4270 LogPrint(BCLog::NET, "disconnecting extra outbound peer=%d (last block announcement received at time %d)\n", pnode->GetId(), oldest_block_announcement);
4271 pnode->fDisconnect = true;
4272 return true;
4273 } else {
4274 LogPrint(BCLog::NET, "keeping outbound peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n", pnode->GetId(), pnode->nTimeConnected, state.nBlocksInFlight);
4275 return false;
4276 }
4277 });
4278 if (disconnected) {
4279 // If we disconnected an extra peer, that means we successfully
4280 // connected to at least one peer after the last time we
4281 // detected a stale tip. Don't try any more extra peers until
4282 // we next detect a stale tip, to limit the load we put on the
4283 // network from these extra connections.
4284 m_connman.SetTryNewOutboundPeer(false);
4285 }
4286 }
4287 }
4288}
4289
4290void PeerManagerImpl::CheckForStaleTipAndEvictPeers()
4291{
4292 LOCK(cs_main);
4293
4294 int64_t time_in_seconds = GetTime();
4295
4296 EvictExtraOutboundPeers(time_in_seconds);
4297
4298 if (time_in_seconds > m_stale_tip_check_time) {
4299 // Check whether our tip is stale, and if so, allow using an extra
4300 // outbound peer
4301 if (!fImporting && !fReindex && m_connman.GetNetworkActive() && m_connman.GetUseAddrmanOutgoing() && TipMayBeStale()) {
4302 LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n", time_in_seconds - m_last_tip_update);
4303 m_connman.SetTryNewOutboundPeer(true);
4304 } else if (m_connman.GetTryNewOutboundPeer()) {
4305 m_connman.SetTryNewOutboundPeer(false);
4306 }
4307 m_stale_tip_check_time = time_in_seconds + STALE_CHECK_INTERVAL;
4308 }
4309
4310 if (!m_initial_sync_finished && CanDirectFetch()) {
4311 m_connman.StartExtraBlockRelayPeers();
4312 m_initial_sync_finished = true;
4313 }
4314}
4315
4316void PeerManagerImpl::MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::microseconds now)
4317{
4318 if (m_connman.ShouldRunInactivityChecks(node_to, std::chrono::duration_cast<std::chrono::seconds>(now).count()) &&
4319 peer.m_ping_nonce_sent &&
4320 now > peer.m_ping_start.load() + std::chrono::seconds{TIMEOUT_INTERVAL}) {
4321 // The ping timeout is using mocktime. To disable the check during
4322 // testing, increase -peertimeout.
4323 LogPrint(BCLog::NET, "ping timeout: %fs peer=%d\n", 0.000001 * count_microseconds(now - peer.m_ping_start.load()), peer.m_id);
4324 node_to.fDisconnect = true;
4325 return;
4326 }
4327
4328 const CNetMsgMaker msgMaker(node_to.GetCommonVersion());
4329 bool pingSend = false;
4330
4331 if (peer.m_ping_queued) {
4332 // RPC ping request by user
4333 pingSend = true;
4334 }
4335
4336 if (peer.m_ping_nonce_sent == 0 && now > peer.m_ping_start.load() + PING_INTERVAL) {
4337 // Ping automatically sent as a latency probe & keepalive.
4338 pingSend = true;
4339 }
4340
4341 if (pingSend) {
4342 uint64_t nonce = 0;
4343 while (nonce == 0) {
4344 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
4345 }
4346 peer.m_ping_queued = false;
4347 peer.m_ping_start = now;
4348 if (node_to.GetCommonVersion() > BIP0031_VERSION) {
4349 peer.m_ping_nonce_sent = nonce;
4350 m_connman.PushMessage(&node_to, msgMaker.Make(NetMsgType::PING, nonce));
4351 } else {
4352 // Peer is too old to support ping command with nonce, pong will never arrive.
4353 peer.m_ping_nonce_sent = 0;
4354 m_connman.PushMessage(&node_to, msgMaker.Make(NetMsgType::PING));
4355 }
4356 }
4357}
4358
4359void PeerManagerImpl::MaybeSendAddr(CNode& node, Peer& peer, std::chrono::microseconds current_time)
4360{
4361 // Nothing to do for non-address-relay peers
4362 if (!peer.m_addr_relay_enabled) return;
4363
4364 LOCK(peer.m_addr_send_times_mutex);
4365 // Periodically advertise our local address to the peer.
4366 if (fListen && !m_chainman.ActiveChainstate().IsInitialBlockDownload() &&
4367 peer.m_next_local_addr_send < current_time) {
4368 // If we've sent before, clear the bloom filter for the peer, so that our
4369 // self-announcement will actually go out.
4370 // This might be unnecessary if the bloom filter has already rolled
4371 // over since our last self-announcement, but there is only a small
4372 // bandwidth cost that we can incur by doing this (which happens
4373 // once a day on average).
4374 if (peer.m_next_local_addr_send != 0us) {
4375 peer.m_addr_known->reset();
4376 }
4377 if (std::optional<CAddress> local_addr = GetLocalAddrForPeer(&node)) {
4378 FastRandomContext insecure_rand;
4379 PushAddress(peer, *local_addr, insecure_rand);
4380 }
4381 peer.m_next_local_addr_send = PoissonNextSend(current_time, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
4382 }
4383
4384 // We sent an `addr` message to this peer recently. Nothing more to do.
4385 if (current_time <= peer.m_next_addr_send) return;
4386
4387 peer.m_next_addr_send = PoissonNextSend(current_time, AVG_ADDRESS_BROADCAST_INTERVAL);
4388
4389 if (!Assume(peer.m_addrs_to_send.size() <= MAX_ADDR_TO_SEND)) {
4390 // Should be impossible since we always check size before adding to
4391 // m_addrs_to_send. Recover by trimming the vector.
4392 peer.m_addrs_to_send.resize(MAX_ADDR_TO_SEND);
4393 }
4394
4395 // Remove addr records that the peer already knows about, and add new
4396 // addrs to the m_addr_known filter on the same pass.
4397 auto addr_already_known = [&peer](const CAddress& addr) {
4398 bool ret = peer.m_addr_known->contains(addr.GetKey());
4399 if (!ret) peer.m_addr_known->insert(addr.GetKey());
4400 return ret;
4401 };
4402 peer.m_addrs_to_send.erase(std::remove_if(peer.m_addrs_to_send.begin(), peer.m_addrs_to_send.end(), addr_already_known),
4403 peer.m_addrs_to_send.end());
4404
4405 // No addr messages to send
4406 if (peer.m_addrs_to_send.empty()) return;
4407
4408 const char* msg_type;
4409 int make_flags;
4410 if (peer.m_wants_addrv2) {
4411 msg_type = NetMsgType::ADDRV2;
4412 make_flags = ADDRV2_FORMAT;
4413 } else {
4414 msg_type = NetMsgType::ADDR;
4415 make_flags = 0;
4416 }
4417 m_connman.PushMessage(&node, CNetMsgMaker(node.GetCommonVersion()).Make(make_flags, msg_type, peer.m_addrs_to_send));
4418 peer.m_addrs_to_send.clear();
4419
4420 // we only send the big addr message once
4421 if (peer.m_addrs_to_send.capacity() > 40) {
4422 peer.m_addrs_to_send.shrink_to_fit();
4423 }
4424}
4425
4426void PeerManagerImpl::MaybeSendFeefilter(CNode& pto, std::chrono::microseconds current_time)
4427{
4429
4430 if (m_ignore_incoming_txs) return;
4431 if (!pto.m_tx_relay) return;
4432 if (pto.GetCommonVersion() < FEEFILTER_VERSION) return;
4433 // peers with the forcerelay permission should not filter txs to us
4435
4436 CAmount currentFilter = m_mempool.GetMinFee(gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
4437 static FeeFilterRounder g_filter_rounder{CFeeRate{DEFAULT_MIN_RELAY_TX_FEE}};
4438
4439 if (m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
4440 // Received tx-inv messages are discarded when the active
4441 // chainstate is in IBD, so tell the peer to not send them.
4442 currentFilter = MAX_MONEY;
4443 } else {
4444 static const CAmount MAX_FILTER{g_filter_rounder.round(MAX_MONEY)};
4445 if (pto.m_tx_relay->lastSentFeeFilter == MAX_FILTER) {
4446 // Send the current filter if we sent MAX_FILTER previously
4447 // and made it out of IBD.
4448 pto.m_tx_relay->m_next_send_feefilter = 0us;
4449 }
4450 }
4451 if (current_time > pto.m_tx_relay->m_next_send_feefilter) {
4452 CAmount filterToSend = g_filter_rounder.round(currentFilter);
4453 // We always have a fee filter of at least minRelayTxFee
4454 filterToSend = std::max(filterToSend, ::minRelayTxFee.GetFeePerK());
4455 if (filterToSend != pto.m_tx_relay->lastSentFeeFilter) {
4456 m_connman.PushMessage(&pto, CNetMsgMaker(pto.GetCommonVersion()).Make(NetMsgType::FEEFILTER, filterToSend));
4457 pto.m_tx_relay->lastSentFeeFilter = filterToSend;
4458 }
4459 pto.m_tx_relay->m_next_send_feefilter = PoissonNextSend(current_time, AVG_FEEFILTER_BROADCAST_INTERVAL);
4460 }
4461 // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
4462 // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
4463 else if (current_time + MAX_FEEFILTER_CHANGE_DELAY < pto.m_tx_relay->m_next_send_feefilter &&
4464 (currentFilter < 3 * pto.m_tx_relay->lastSentFeeFilter / 4 || currentFilter > 4 * pto.m_tx_relay->lastSentFeeFilter / 3)) {
4465 pto.m_tx_relay->m_next_send_feefilter = current_time + GetRandomDuration<std::chrono::microseconds>(MAX_FEEFILTER_CHANGE_DELAY);
4466 }
4467}
4468
4469namespace {
4470class CompareInvMempoolOrder
4471{
4472 CTxMemPool *mp;
4473 bool m_wtxid_relay;
4474public:
4475 explicit CompareInvMempoolOrder(CTxMemPool *_mempool, bool use_wtxid)
4476 {
4477 mp = _mempool;
4478 m_wtxid_relay = use_wtxid;
4479 }
4480
4481 bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b)
4482 {
4483 /* As std::make_heap produces a max-heap, we want the entries with the
4484 * fewest ancestors/highest fee to sort later. */
4485 return mp->CompareDepthAndScore(*b, *a, m_wtxid_relay);
4486 }
4487};
4488}
4489
4490bool PeerManagerImpl::SetupAddressRelay(const CNode& node, Peer& peer)
4491{
4492 // We don't participate in addr relay with outbound block-relay-only
4493 // connections to prevent providing adversaries with the additional
4494 // information of addr traffic to infer the link.
4495 if (node.IsBlockOnlyConn()) return false;
4496
4497 if (!peer.m_addr_relay_enabled.exchange(true)) {
4498 // First addr message we have received from the peer, initialize
4499 // m_addr_known
4500 peer.m_addr_known = std::make_unique<CRollingBloomFilter>(5000, 0.001);
4501 }
4502
4503 return true;
4504}
4505
4506bool PeerManagerImpl::SendMessages(CNode* pto)
4507{
4508 PeerRef peer = GetPeerRef(pto->GetId());
4509 if (!peer) return false;
4510 const Consensus::Params& consensusParams = m_chainparams.GetConsensus();
4511
4512 // We must call MaybeDiscourageAndDisconnect first, to ensure that we'll
4513 // disconnect misbehaving peers even before the version handshake is complete.
4514 if (MaybeDiscourageAndDisconnect(*pto, *peer)) return true;
4515
4516 // Don't send anything until the version handshake is complete
4517 if (!pto->fSuccessfullyConnected || pto->fDisconnect)
4518 return true;
4519
4520 // If we get here, the outgoing message serialization version is set and can't change.
4521 const CNetMsgMaker msgMaker(pto->GetCommonVersion());
4522
4523 const auto current_time = GetTime<std::chrono::microseconds>();
4524
4525 if (pto->IsAddrFetchConn() && current_time - std::chrono::seconds(pto->nTimeConnected) > 10 * AVG_ADDRESS_BROADCAST_INTERVAL) {
4526 LogPrint(BCLog::NET, "addrfetch connection timeout; disconnecting peer=%d\n", pto->GetId());
4527 pto->fDisconnect = true;
4528 return true;
4529 }
4530
4531 MaybeSendPing(*pto, *peer, current_time);
4532
4533 // MaybeSendPing may have marked peer for disconnection
4534 if (pto->fDisconnect) return true;
4535
4536 MaybeSendAddr(*pto, *peer, current_time);
4537
4538 {
4539 LOCK(cs_main);
4540
4541 CNodeState &state = *State(pto->GetId());
4542
4543 // Start block sync
4544 if (pindexBestHeader == nullptr)
4545 pindexBestHeader = m_chainman.ActiveChain().Tip();
4546 bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->IsAddrFetchConn()); // Download if this is a nice peer, or we have no nice peers and this one might do.
4547 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
4548 // Only actively request headers from a single peer, unless we're close to today.
4549 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
4550 state.fSyncStarted = true;
4551 state.m_headers_sync_timeout = current_time + HEADERS_DOWNLOAD_TIMEOUT_BASE +
4552 (
4553 // Convert HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER to microseconds before scaling
4554 // to maintain precision
4555 std::chrono::microseconds{HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER} *
4557 );
4558 nSyncStarted++;
4559 const CBlockIndex *pindexStart = pindexBestHeader;
4560 /* If possible, start at the block preceding the currently
4561 best known header. This ensures that we always get a
4562 non-empty list of headers back as long as the peer
4563 is up-to-date. With a non-empty response, we can initialise
4564 the peer's known best block. This wouldn't be possible
4565 if we requested starting at pindexBestHeader and
4566 got back an empty response. */
4567 if (pindexStart->pprev)
4568 pindexStart = pindexStart->pprev;
4569 LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), peer->m_starting_height);
4570 m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, m_chainman.ActiveChain().GetLocator(pindexStart), uint256()));
4571 }
4572 }
4573
4574 //
4575 // Try sending block announcements via headers
4576 //
4577 {
4578 // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
4579 // list of block hashes we're relaying, and our peer wants
4580 // headers announcements, then find the first header
4581 // not yet known to our peer but would connect, and send.
4582 // If no header would connect, or if we have too many
4583 // blocks, or if the peer doesn't want headers, just
4584 // add all to the inv queue.
4585 LOCK(peer->m_block_inv_mutex);
4586 std::vector<CBlock> vHeaders;
4587 bool fRevertToInv = ((!state.fPreferHeaders &&
4588 (!state.fPreferHeaderAndIDs || peer->m_blocks_for_headers_relay.size() > 1)) ||
4589 peer->m_blocks_for_headers_relay.size() > MAX_BLOCKS_TO_ANNOUNCE);
4590 const CBlockIndex *pBestIndex = nullptr; // last header queued for delivery
4591 ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date
4592
4593 if (!fRevertToInv) {
4594 bool fFoundStartingHeader = false;
4595 // Try to find first header that our peer doesn't have, and
4596 // then send all headers past that one. If we come across any
4597 // headers that aren't on m_chainman.ActiveChain(), give up.
4598 for (const uint256& hash : peer->m_blocks_for_headers_relay) {
4599 const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hash);
4600 assert(pindex);
4601 if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) {
4602 // Bail out if we reorged away from this block
4603 fRevertToInv = true;
4604 break;
4605 }
4606 if (pBestIndex != nullptr && pindex->pprev != pBestIndex) {
4607 // This means that the list of blocks to announce don't
4608 // connect to each other.
4609 // This shouldn't really be possible to hit during
4610 // regular operation (because reorgs should take us to
4611 // a chain that has some block not on the prior chain,
4612 // which should be caught by the prior check), but one
4613 // way this could happen is by using invalidateblock /
4614 // reconsiderblock repeatedly on the tip, causing it to
4615 // be added multiple times to m_blocks_for_headers_relay.
4616 // Robustly deal with this rare situation by reverting
4617 // to an inv.
4618 fRevertToInv = true;
4619 break;
4620 }
4621 pBestIndex = pindex;
4622 if (fFoundStartingHeader) {
4623 // add this to the headers message
4624 vHeaders.push_back(pindex->GetBlockHeader());
4625 } else if (PeerHasHeader(&state, pindex)) {
4626 continue; // keep looking for the first new block
4627 } else if (pindex->pprev == nullptr || PeerHasHeader(&state, pindex->pprev)) {
4628 // Peer doesn't have this header but they do have the prior one.
4629 // Start sending headers.
4630 fFoundStartingHeader = true;
4631 vHeaders.push_back(pindex->GetBlockHeader());
4632 } else {
4633 // Peer doesn't have this header or the prior one -- nothing will
4634 // connect, so bail out.
4635 fRevertToInv = true;
4636 break;
4637 }
4638 }
4639 }
4640 if (!fRevertToInv && !vHeaders.empty()) {
4641 if (vHeaders.size() == 1 && state.fPreferHeaderAndIDs) {
4642 // We only send up to 1 block as header-and-ids, as otherwise
4643 // probably means we're doing an initial-ish-sync or they're slow
4644 LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__,
4645 vHeaders.front().GetHash().ToString(), pto->GetId());
4646
4647 int nSendFlags = state.fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
4648
4649 bool fGotBlockFromCache = false;
4650 {
4652 if (most_recent_block_hash == pBestIndex->GetBlockHash()) {
4653 if (state.fWantsCmpctWitness || !fWitnessesPresentInMostRecentCompactBlock)
4654 m_connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *most_recent_compact_block));
4655 else {
4656 CBlockHeaderAndShortTxIDs cmpctblock(*most_recent_block, state.fWantsCmpctWitness);
4657 m_connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
4658 }
4659 fGotBlockFromCache = true;
4660 }
4661 }
4662 if (!fGotBlockFromCache) {
4663 CBlock block;
4664 bool ret = ReadBlockFromDisk(block, pBestIndex, consensusParams);
4665 assert(ret);
4666 CBlockHeaderAndShortTxIDs cmpctblock(block, state.fWantsCmpctWitness);
4667 m_connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
4668 }
4669 state.pindexBestHeaderSent = pBestIndex;
4670 } else if (state.fPreferHeaders) {
4671 if (vHeaders.size() > 1) {
4672 LogPrint(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
4673 vHeaders.size(),
4674 vHeaders.front().GetHash().ToString(),
4675 vHeaders.back().GetHash().ToString(), pto->GetId());
4676 } else {
4677 LogPrint(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__,
4678 vHeaders.front().GetHash().ToString(), pto->GetId());
4679 }
4680 m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
4681 state.pindexBestHeaderSent = pBestIndex;
4682 } else
4683 fRevertToInv = true;
4684 }
4685 if (fRevertToInv) {
4686 // If falling back to using an inv, just try to inv the tip.
4687 // The last entry in m_blocks_for_headers_relay was our tip at some point
4688 // in the past.
4689 if (!peer->m_blocks_for_headers_relay.empty()) {
4690 const uint256& hashToAnnounce = peer->m_blocks_for_headers_relay.back();
4691 const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(hashToAnnounce);
4692 assert(pindex);
4693
4694 // Warn if we're announcing a block that is not on the main chain.
4695 // This should be very rare and could be optimized out.
4696 // Just log for now.
4697 if (m_chainman.ActiveChain()[pindex->nHeight] != pindex) {
4698 LogPrint(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n",
4699 hashToAnnounce.ToString(), m_chainman.ActiveChain().Tip()->GetBlockHash().ToString());
4700 }
4701
4702 // If the peer's chain has this block, don't inv it back.
4703 if (!PeerHasHeader(&state, pindex)) {
4704 peer->m_blocks_for_inv_relay.push_back(hashToAnnounce);
4705 LogPrint(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__,
4706 pto->GetId(), hashToAnnounce.ToString());
4707 }
4708 }
4709 }
4710 peer->m_blocks_for_headers_relay.clear();
4711 }
4712
4713 //
4714 // Message: inventory
4715 //
4716 std::vector<CInv> vInv;
4717 {
4718 LOCK(peer->m_block_inv_mutex);
4719 vInv.reserve(std::max<size_t>(peer->m_blocks_for_inv_relay.size(), INVENTORY_BROADCAST_MAX));
4720
4721 // Add blocks
4722 for (const uint256& hash : peer->m_blocks_for_inv_relay) {
4723 vInv.push_back(CInv(MSG_BLOCK, hash));
4724 if (vInv.size() == MAX_INV_SZ) {
4725 m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
4726 vInv.clear();
4727 }
4728 }
4729 peer->m_blocks_for_inv_relay.clear();
4730 }
4731
4732 if (pto->m_tx_relay != nullptr) {
4733 LOCK(pto->m_tx_relay->cs_tx_inventory);
4734 // Check whether periodic sends should happen
4735 bool fSendTrickle = pto->HasPermission(NetPermissionFlags::NoBan);
4736 if (pto->m_tx_relay->nNextInvSend < current_time) {
4737 fSendTrickle = true;
4738 if (pto->IsInboundConn()) {
4739 pto->m_tx_relay->nNextInvSend = m_connman.PoissonNextSendInbound(current_time, INBOUND_INVENTORY_BROADCAST_INTERVAL);
4740 } else {
4741 pto->m_tx_relay->nNextInvSend = PoissonNextSend(current_time, OUTBOUND_INVENTORY_BROADCAST_INTERVAL);
4742 }
4743 }
4744
4745 // Time to send but the peer has requested we not relay transactions.
4746 if (fSendTrickle) {
4747 LOCK(pto->m_tx_relay->cs_filter);
4748 if (!pto->m_tx_relay->fRelayTxes) pto->m_tx_relay->setInventoryTxToSend.clear();
4749 }
4750
4751 // Respond to BIP35 mempool requests
4752 if (fSendTrickle && pto->m_tx_relay->fSendMempool) {
4753 auto vtxinfo = m_mempool.infoAll();
4754 pto->m_tx_relay->fSendMempool = false;
4755 const CFeeRate filterrate{pto->m_tx_relay->minFeeFilter.load()};
4756
4757 LOCK(pto->m_tx_relay->cs_filter);
4758
4759 for (const auto& txinfo : vtxinfo) {
4760 const uint256& hash = state.m_wtxid_relay ? txinfo.tx->GetWitnessHash() : txinfo.tx->GetHash();
4761 CInv inv(state.m_wtxid_relay ? MSG_WTX : MSG_TX, hash);
4762 pto->m_tx_relay->setInventoryTxToSend.erase(hash);
4763 // Don't send transactions that peers will not put into their mempool
4764 if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
4765 continue;
4766 }
4767 if (pto->m_tx_relay->pfilter) {
4768 if (!pto->m_tx_relay->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
4769 }
4770 pto->m_tx_relay->filterInventoryKnown.insert(hash);
4771 // Responses to MEMPOOL requests bypass the m_recently_announced_invs filter.
4772 vInv.push_back(inv);
4773 if (vInv.size() == MAX_INV_SZ) {
4774 m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
4775 vInv.clear();
4776 }
4777 }
4778 pto->m_tx_relay->m_last_mempool_req = std::chrono::duration_cast<std::chrono::seconds>(current_time);
4779 }
4780
4781 // Determine transactions to relay
4782 if (fSendTrickle) {
4783 // Produce a vector with all candidates for sending
4784 std::vector<std::set<uint256>::iterator> vInvTx;
4785 vInvTx.reserve(pto->m_tx_relay->setInventoryTxToSend.size());
4786 for (std::set<uint256>::iterator it = pto->m_tx_relay->setInventoryTxToSend.begin(); it != pto->m_tx_relay->setInventoryTxToSend.end(); it++) {
4787 vInvTx.push_back(it);
4788 }
4789 const CFeeRate filterrate{pto->m_tx_relay->minFeeFilter.load()};
4790 // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
4791 // A heap is used so that not all items need sorting if only a few are being sent.
4792 CompareInvMempoolOrder compareInvMempoolOrder(&m_mempool, state.m_wtxid_relay);
4793 std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
4794 // No reason to drain out at many times the network's capacity,
4795 // especially since we have many peers and some will draw much shorter delays.
4796 unsigned int nRelayedTransactions = 0;
4797 LOCK(pto->m_tx_relay->cs_filter);
4798 while (!vInvTx.empty() && nRelayedTransactions < INVENTORY_BROADCAST_MAX) {
4799 // Fetch the top element from the heap
4800 std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
4801 std::set<uint256>::iterator it = vInvTx.back();
4802 vInvTx.pop_back();
4803 uint256 hash = *it;
4804 CInv inv(state.m_wtxid_relay ? MSG_WTX : MSG_TX, hash);
4805 // Remove it from the to-be-sent set
4806 pto->m_tx_relay->setInventoryTxToSend.erase(it);
4807 // Check if not in the filter already
4808 if (pto->m_tx_relay->filterInventoryKnown.contains(hash)) {
4809 continue;
4810 }
4811 // Not in the mempool anymore? don't bother sending it.
4812 auto txinfo = m_mempool.info(ToGenTxid(inv));
4813 if (!txinfo.tx) {
4814 continue;
4815 }
4816 auto txid = txinfo.tx->GetHash();
4817 auto wtxid = txinfo.tx->GetWitnessHash();
4818 // Peer told you to not send transactions at that feerate? Don't bother sending it.
4819 if (txinfo.fee < filterrate.GetFee(txinfo.vsize)) {
4820 continue;
4821 }
4822 if (pto->m_tx_relay->pfilter && !pto->m_tx_relay->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
4823 // Send
4824 State(pto->GetId())->m_recently_announced_invs.insert(hash);
4825 vInv.push_back(inv);
4826 nRelayedTransactions++;
4827 {
4828 // Expire old relay messages
4829 while (!g_relay_expiration.empty() && g_relay_expiration.front().first < current_time)
4830 {
4831 mapRelay.erase(g_relay_expiration.front().second);
4832 g_relay_expiration.pop_front();
4833 }
4834
4835 auto ret = mapRelay.emplace(txid, std::move(txinfo.tx));
4836 if (ret.second) {
4837 g_relay_expiration.emplace_back(current_time + RELAY_TX_CACHE_TIME, ret.first);
4838 }
4839 // Add wtxid-based lookup into mapRelay as well, so that peers can request by wtxid
4840 auto ret2 = mapRelay.emplace(wtxid, ret.first->second);
4841 if (ret2.second) {
4842 g_relay_expiration.emplace_back(current_time + RELAY_TX_CACHE_TIME, ret2.first);
4843 }
4844 }
4845 if (vInv.size() == MAX_INV_SZ) {
4846 m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
4847 vInv.clear();
4848 }
4849 pto->m_tx_relay->filterInventoryKnown.insert(hash);
4850 if (hash != txid) {
4851 // Insert txid into filterInventoryKnown, even for
4852 // wtxidrelay peers. This prevents re-adding of
4853 // unconfirmed parents to the recently_announced
4854 // filter, when a child tx is requested. See
4855 // ProcessGetData().
4856 pto->m_tx_relay->filterInventoryKnown.insert(txid);
4857 }
4858 }
4859 }
4860 }
4861 if (!vInv.empty())
4862 m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
4863
4864 // Detect whether we're stalling
4865 if (state.m_stalling_since.count() && state.m_stalling_since < current_time - BLOCK_STALLING_TIMEOUT) {
4866 // Stalling only triggers when the block download window cannot move. During normal steady state,
4867 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
4868 // should only happen during initial block download.
4869 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->GetId());
4870 pto->fDisconnect = true;
4871 return true;
4872 }
4873 // In case there is a block that has been in flight from this peer for block_interval * (1 + 0.5 * N)
4874 // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
4875 // We compensate for other peers to prevent killing off peers due to our own downstream link
4876 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
4877 // to unreasonably increase our timeout.
4878 if (state.vBlocksInFlight.size() > 0) {
4879 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
4880 int nOtherPeersWithValidatedDownloads = m_peers_downloading_from - 1;
4881 if (current_time > state.m_downloading_since + std::chrono::seconds{consensusParams.nPowTargetSpacing} * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
4882 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.pindex->GetBlockHash().ToString(), pto->GetId());
4883 pto->fDisconnect = true;
4884 return true;
4885 }
4886 }
4887 // Check for headers sync timeouts
4888 if (state.fSyncStarted && state.m_headers_sync_timeout < std::chrono::microseconds::max()) {
4889 // Detect whether this is a stalling initial-headers-sync peer
4890 if (pindexBestHeader->GetBlockTime() <= GetAdjustedTime() - 24 * 60 * 60) {
4891 if (current_time > state.m_headers_sync_timeout && nSyncStarted == 1 && (nPreferredDownload - state.fPreferredDownload >= 1)) {
4892 // Disconnect a peer (without NetPermissionFlags::NoBan permission) if it is our only sync peer,
4893 // and we have others we could be using instead.
4894 // Note: If all our peers are inbound, then we won't
4895 // disconnect our sync peer for stalling; we have bigger
4896 // problems if we can't get any outbound peers.
4898 LogPrintf("Timeout downloading headers from peer=%d, disconnecting\n", pto->GetId());
4899 pto->fDisconnect = true;
4900 return true;
4901 } else {
4902 LogPrintf("Timeout downloading headers from noban peer=%d, not disconnecting\n", pto->GetId());
4903 // Reset the headers sync state so that we have a
4904 // chance to try downloading from a different peer.
4905 // Note: this will also result in at least one more
4906 // getheaders message to be sent to
4907 // this peer (eventually).
4908 state.fSyncStarted = false;
4909 nSyncStarted--;
4910 state.m_headers_sync_timeout = 0us;
4911 }
4912 }
4913 } else {
4914 // After we've caught up once, reset the timeout so we can't trigger
4915 // disconnect later.
4916 state.m_headers_sync_timeout = std::chrono::microseconds::max();
4917 }
4918 }
4919
4920 // Check that outbound peers have reasonable chains
4921 // GetTime() is used by this anti-DoS logic so we can test this using mocktime
4922 ConsiderEviction(*pto, GetTime());
4923
4924 //
4925 // Message: getdata (blocks)
4926 //
4927 std::vector<CInv> vGetData;
4928 if (!pto->fClient && ((fFetch && !pto->m_limited_node) || !m_chainman.ActiveChainstate().IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4929 std::vector<const CBlockIndex*> vToDownload;
4930 NodeId staller = -1;
4931 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
4932 for (const CBlockIndex *pindex : vToDownload) {
4933 uint32_t nFetchFlags = GetFetchFlags(*pto);
4934 vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
4935 BlockRequested(pto->GetId(), *pindex);
4936 LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
4937 pindex->nHeight, pto->GetId());
4938 }
4939 if (state.nBlocksInFlight == 0 && staller != -1) {
4940 if (State(staller)->m_stalling_since == 0us) {
4941 State(staller)->m_stalling_since = current_time;
4942 LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
4943 }
4944 }
4945 }
4946
4947 //
4948 // Message: getdata (transactions)
4949 //
4950 std::vector<std::pair<NodeId, GenTxid>> expired;
4951 auto requestable = m_txrequest.GetRequestable(pto->GetId(), current_time, &expired);
4952 for (const auto& entry : expired) {
4953 LogPrint(BCLog::NET, "timeout of inflight %s %s from peer=%d\n", entry.second.IsWtxid() ? "wtx" : "tx",
4954 entry.second.GetHash().ToString(), entry.first);
4955 }
4956 for (const GenTxid& gtxid : requestable) {
4957 if (!AlreadyHaveTx(gtxid)) {
4958 LogPrint(BCLog::NET, "Requesting %s %s peer=%d\n", gtxid.IsWtxid() ? "wtx" : "tx",
4959 gtxid.GetHash().ToString(), pto->GetId());
4960 vGetData.emplace_back(gtxid.IsWtxid() ? MSG_WTX : (MSG_TX | GetFetchFlags(*pto)), gtxid.GetHash());
4961 if (vGetData.size() >= MAX_GETDATA_SZ) {
4962 m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
4963 vGetData.clear();
4964 }
4965 m_txrequest.RequestedTx(pto->GetId(), gtxid.GetHash(), current_time + GETDATA_TX_INTERVAL);
4966 } else {
4967 // We have already seen this transaction, no need to download. This is just a belt-and-suspenders, as
4968 // this should already be called whenever a transaction becomes AlreadyHaveTx().
4969 m_txrequest.ForgetTxHash(gtxid.GetHash());
4970 }
4971 }
4972
4973
4974 if (!vGetData.empty())
4975 m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
4976
4977 MaybeSendFeefilter(*pto, current_time);
4978 } // release cs_main
4979 return true;
4980}
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:26
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:118
@ READ_STATUS_OK
@ READ_STATUS_INVALID
@ READ_STATUS_FAILED
enum ReadStatus_t ReadStatus
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
BlockFilterType
Definition: blockfilter.h:89
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
static constexpr int CFCHECKPT_INTERVAL
Interval between compact filter checkpoints.
bool ReadRawBlockFromDisk(std::vector< uint8_t > &block, const FlatFilePos &pos, const CMessageHeader::MessageStartChars &message_start)
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
bool fPruneMode
True if we're running in -prune mode.
std::atomic_bool fReindex
std::atomic_bool fImporting
int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, const CBlockIndex &from, const CBlockIndex &tip, const Consensus::Params &params)
Return the time it would take to redo the work difference between from and to, assuming the current h...
Definition: chain.cpp:137
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition: chain.cpp:156
@ BLOCK_VALID_CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
Definition: chain.h:112
@ BLOCK_VALID_TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
Definition: chain.h:108
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:115
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:101
@ BLOCK_HAVE_DATA
full block available in blk*.dat
Definition: chain.h:121
#define Assume(val)
Assume is the identity function.
Definition: check.h:72
Stochastic address manager.
Definition: addrman.h:55
bool Add(const std::vector< CAddress > &vAddr, const CNetAddr &source, int64_t nTimePenalty=0)
Attempt to add one or more addresses to addrman's new table.
Definition: addrman.cpp:1153
void Good(const CService &addr, int64_t nTime=GetAdjustedTime())
Mark an entry as accessible, possibly moving it from "new" to "tried".
Definition: addrman.cpp:1158
void Connected(const CService &addr, int64_t nTime=GetAdjustedTime())
We have successfully connected to this peer.
Definition: addrman.cpp:1188
void SetServices(const CService &addr, ServiceFlags nServices)
Update an entry's service bits.
Definition: addrman.cpp:1193
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: system.cpp:596
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:602
Definition: banman.h:59
void Discourage(const CNetAddr &net_addr)
Definition: banman.cpp:110
bool IsBanned(const CNetAddr &net_addr)
Return whether net_addr is banned.
Definition: banman.cpp:75
bool IsDiscouraged(const CNetAddr &net_addr)
Return whether net_addr is discouraged.
Definition: banman.cpp:69
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
bool LookupFilterRange(int start_height, const CBlockIndex *stop_index, std::vector< BlockFilter > &filters_out) const
Get a range of filters between two heights on a chain.
bool LookupFilterHeader(const CBlockIndex *block_index, uint256 &header_out)
Get a single filter header by block.
bool LookupFilterHashRange(int start_height, const CBlockIndex *stop_index, std::vector< uint256 > &hashes_out) const
Get a range of filter hashes between two heights on a chain.
std::vector< CTransactionRef > txn
std::vector< uint16_t > indexes
A CService with information about it as peer.
Definition: protocol.h:359
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
Definition: protocol.h:442
uint32_t nTime
Always included in serialization.
Definition: protocol.h:440
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:21
uint256 hashPrevBlock
Definition: block.h:25
uint256 GetHash() const
Definition: block.cpp:11
Definition: block.h:63
std::vector< CTransactionRef > vtx
Definition: block.h:66
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:146
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:152
CBlockHeader GetBlockHeader() const
Definition: chain.h:241
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:170
bool HaveTxsDownloaded() const
Check whether this block's and all previous blocks' transactions have been downloaded (and stored to ...
Definition: chain.h:266
uint256 GetBlockHash() const
Definition: chain.h:254
int64_t GetBlockTime() const
Definition: chain.h:268
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:177
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:303
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:111
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:158
uint32_t nStatus
Verification status of this block.
Definition: chain.h:195
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
Definition: bloom.h:45
bool IsWithinSizeConstraints() const
True if the size is <= MAX_BLOOM_FILTER_SIZE and the number of hash functions is <= MAX_HASH_FUNCS (c...
Definition: bloom.cpp:88
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:421
CBlockLocator GetLocator(const CBlockIndex *pindex=nullptr) const
Return a CBlockLocator that refers to a block in this chain (by default the tip).
Definition: chain.cpp:23
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
Definition: chain.h:438
int Height() const
Return the maximal height in the chain.
Definition: chain.h:446
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:433
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:70
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:82
const CMessageHeader::MessageStartChars & MessageStart() const
Definition: chainparams.h:83
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:544
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr) LOCKS_EXCLUDED(cs_main)
Find the best known block, and make it the tip of the block chain.
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:638
void UnloadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:620
Definition: net.h:741
void ForEachNode(const NodeFn &func)
Definition: net.h:824
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached if param historicalBlockServingLimit is set true,...
Definition: net.cpp:2932
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3063
bool GetNetworkActive() const
Definition: net.h:813
bool GetTryNewOutboundPeer() const
Definition: net.cpp:1796
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:1801
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:2978
bool ShouldRunInactivityChecks(const CNode &node, int64_t secs_now) const
Return true if we should disconnect the peer for failing an inactivity check.
Definition: net.cpp:1320
int GetExtraBlockRelayCount() const
Definition: net.cpp:1827
void StartExtraBlockRelayPeers()
Definition: net.h:864
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2841
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3093
int GetExtraFullOutboundCount() const
Definition: net.cpp:1813
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct, std::optional< Network > network) const
Return all or many randomly selected addresses, optionally by network.
Definition: net.cpp:2738
void WakeMessageHandler()
Definition: net.cpp:1649
std::chrono::microseconds PoissonNextSendInbound(std::chrono::microseconds now, std::chrono::seconds average_interval)
Attempts to obfuscate tx time through exponentially distributed emitting.
Definition: net.cpp:3076
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:376
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:3022
bool GetUseAddrmanOutgoing() const
Definition: net.h:814
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:205
int GetType() const
Definition: streams.h:361
int GetVersion() const
Definition: streams.h:363
int in_avail() const
Definition: streams.h:358
void ignore(int nSize)
Definition: streams.h:384
bool empty() const
Definition: streams.h:256
size_type size() const
Definition: streams.h:255
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:30
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:57
inv message data
Definition: protocol.h:477
bool IsMsgCmpctBlk() const
Definition: protocol.h:494
bool IsMsgBlk() const
Definition: protocol.h:491
std::string ToString() const
Definition: protocol.cpp:170
bool IsMsgWtx() const
Definition: protocol.h:492
uint32_t type
Definition: protocol.h:507
bool IsGenTxMsg() const
Definition: protocol.h:498
bool IsMsgTx() const
Definition: protocol.h:490
bool IsMsgFilteredBlk() const
Definition: protocol.h:493
uint256 hash
Definition: protocol.h:508
bool IsGenBlkMsg() const
Definition: protocol.h:502
bool IsMsgWitnessBlk() const
Definition: protocol.h:495
Used to relay blocks as header + vector<merkle branch> to filtered nodes.
Definition: merkleblock.h:125
std::vector< std::pair< unsigned int, uint256 > > vMatchedTxn
Public only for unit testing and relay testing (not relayed).
Definition: merkleblock.h:137
bool IsRelayable() const
Whether this address should be relayed to other peers even if we can't reach it ourselves.
Definition: netaddress.h:225
void SetIP(const CNetAddr &ip)
Definition: netaddress.cpp:107
bool IsRoutable() const
Definition: netaddress.cpp:490
bool IsValid() const
Definition: netaddress.cpp:451
bool IsLocal() const
Definition: netaddress.cpp:425
uint64_t GetHash() const
Definition: netaddress.cpp:836
bool IsAddrV1Compatible() const
Check if the current object can be serialized in pre-ADDRv2/BIP155 format.
Definition: netaddress.cpp:505
Transport protocol agnostic message container.
Definition: net.h:282
CSerializedNetMsg Make(int nFlags, std::string msg_type, Args &&... args) const
Information about a peer.
Definition: net.h:394
RecursiveMutex cs_vProcessMsg
Definition: net.h:415
bool IsFeelerConn() const
Definition: net.h:487
bool ExpectServicesFromConn() const
Definition: net.h:499
std::atomic< int > nVersion
Definition: net.h:435
bool IsInboundConn() const
Definition: net.h:495
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:443
std::atomic_bool fPauseRecv
Definition: net.h:457
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:460
NodeId GetId() const
Definition: net.h:585
bool IsManualConn() const
Definition: net.h:479
void PushTxInventory(const uint256 &hash)
Definition: net.h:643
std::atomic< int64_t > nTimeOffset
Definition: net.h:427
const std::string m_addr_name
Definition: net.h:432
std::string ConnectionTypeAsString() const
Definition: net.h:661
void SetCommonVersion(int greatest_common_version)
Definition: net.h:610
std::atomic< bool > m_bip152_highbandwidth_to
Definition: net.h:527
size_t nProcessQueueSize
Definition: net.h:417
void SetAddrLocal(const CService &addrLocalIn)
May not be called more than once.
Definition: net.cpp:559
std::atomic< bool > m_bip152_highbandwidth_from
Definition: net.h:529
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:664
std::atomic_bool fSuccessfullyConnected
fSuccessfullyConnected is set to true on receiving VERACK from the peer.
Definition: net.h:449
bool IsAddrFetchConn() const
Definition: net.h:491
uint64_t GetLocalNonce() const
Definition: net.h:589
std::atomic< ServiceFlags > nServices
Definition: net.h:403
RecursiveMutex cs_SubVer
Definition: net.h:436
const CAddress addr
Definition: net.h:429
const int64_t nTimeConnected
Unix epoch time at peer connection, in seconds.
Definition: net.h:426
bool IsBlockOnlyConn() const
Definition: net.h:483
int GetCommonVersion() const
Definition: net.h:615
bool IsFullOutboundConn() const
Definition: net.h:475
bool fClient
Definition: net.h:446
std::atomic_bool fPauseSend
Definition: net.h:458
std::unique_ptr< TxRelay > m_tx_relay
Definition: net.h:558
std::atomic< int64_t > nLastTXTime
UNIX epoch time of the last transaction received from this peer that we had not yet seen (e....
Definition: net.h:571
ServiceFlags GetLocalServices() const
Definition: net.h:656
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition: net.h:434
void AddKnownTx(const uint256 &hash)
Definition: net.h:635
bool m_limited_node
Definition: net.h:447
std::atomic< int64_t > nLastBlockTime
UNIX epoch time of the last block received from this peer that we had not yet seen (e....
Definition: net.h:565
std::atomic_bool fDisconnect
Definition: net.h:452
uint256 hash
Definition: transaction.h:29
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set.
Definition: bloom.h:109
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:34
void scheduleFromNow(Function f, std::chrono::milliseconds delta)
Call f once after the delta has passed.
Definition: scheduler.h:47
void scheduleEvery(Function f, std::chrono::milliseconds delta)
Repeat f until the scheduler is stopped.
Definition: scheduler.cpp:112
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:523
std::string ToString() const
std::vector< unsigned char > GetKey() const
SipHash-2-4.
Definition: siphash.h:14
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
Definition: siphash.cpp:76
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data It is treated as if this was the little-endian interpretation of ...
Definition: siphash.cpp:28
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:260
const uint256 & GetWitnessHash() const
Definition: transaction.h:303
bool HasWitness() const
Definition: transaction.h:332
const uint256 & GetHash() const
Definition: transaction.h:302
const std::vector< CTxIn > vin
Definition: transaction.h:270
An input of a transaction.
Definition: transaction.h:66
COutPoint prevout
Definition: transaction.h:68
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:80
std::set< CTxMemPoolEntryRef, CompareIteratorByHash > Parents
Definition: txmempool.h:84
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:424
void RemoveUnbroadcastTx(const uint256 &txid, const bool unchecked=false)
Removes a transaction from the unbroadcast set.
Definition: txmempool.cpp:1044
std::set< uint256 > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
Definition: txmempool.h:758
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:511
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
Definition: txmempool.cpp:1109
std::optional< txiter > GetIter(const uint256 &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given hash, if found.
Definition: txmempool.cpp:981
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:911
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:1038
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:897
TxMempoolInfo info(const GenTxid &gtxid) const
Definition: txmempool.cpp:920
bool exists(const GenTxid &gtxid) const
Definition: txmempool.h:725
bool CompareDepthAndScore(const uint256 &hasha, const uint256 &hashb, bool wtxid=false)
Definition: txmempool.cpp:835
unsigned long size() const
Definition: txmempool.h:707
virtual void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr< const CBlock > &block)
Notifies listeners that a block which builds directly on our current tip has been received and connec...
virtual void BlockChecked(const CBlock &, const BlockValidationState &)
Notifies listeners of a block validation result.
virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
Notifies listeners when the block chain tip advances.
virtual void BlockConnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being connected.
virtual void BlockDisconnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being disconnected.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:847
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > &block, bool force_processing, bool *new_block) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
CChainState & ActiveChainstate() const
The most-work chain.
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, BlockValidationState &state, const CChainParams &chainparams, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
CChain & ActiveChain() const
Definition: validation.h:945
Fast randomness source.
Definition: random.h:120
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:190
A generic txid reference (txid or wtxid).
Definition: transaction.h:391
bool IsWtxid() const
Definition: transaction.h:399
const uint256 & GetHash() const
Definition: transaction.h:400
static GenTxid Wtxid(const uint256 &hash)
Definition: transaction.h:398
static GenTxid Txid(const uint256 &hash)
Definition: transaction.h:397
virtual void FinalizeNode(const CNode &node)=0
Handle removal of a peer (clear state)
virtual void InitializeNode(CNode *pnode)=0
Initialize a peer (setup state, queue any initial messages)
virtual bool SendMessages(CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(pnode -> cs_sendProcessing)=0
Send queued protocol messages to a given node.
virtual bool ProcessMessages(CNode *pnode, std::atomic< bool > &interrupt)=0
Process protocol messages received from a given node.
ReadStatus InitData(const CBlockHeaderAndShortTxIDs &cmpctblock, const std::vector< std::pair< uint256, CTransactionRef > > &extra_txn)
bool IsTxAvailable(size_t index) const
ReadStatus FillBlock(CBlock &block, const std::vector< CTransactionRef > &vtx_missing)
virtual void RelayTransaction(const uint256 &txid, const uint256 &wtxid)=0
Relay transaction to all peers.
virtual void ProcessMessage(CNode &pfrom, const std::string &msg_type, CDataStream &vRecv, const std::chrono::microseconds time_received, const std::atomic< bool > &interruptMsgProc)=0
Process a single message from a peer.
static std::unique_ptr< PeerManager > make(const CChainParams &chainparams, CConnman &connman, AddrMan &addrman, BanMan *banman, ChainstateManager &chainman, CTxMemPool &pool, bool ignore_incoming_txs)
virtual void SendPings()=0
Send ping message to all peers.
virtual void StartScheduledTasks(CScheduler &scheduler)=0
Begin running background tasks, should only be called once.
virtual void SetBestHeight(int height)=0
Set the best height.
virtual bool IgnoresIncomingTxs()=0
Whether this node ignores txs received over p2p.
virtual void Misbehaving(const NodeId pnode, const int howmuch, const std::string &message)=0
Increment peer's misbehavior score.
virtual bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) const =0
Get statistics from node state.
virtual void CheckForStaleTipAndEvictPeers()=0
Evict extra outbound peers.
A class to track orphan transactions (failed on TX_MISSING_INPUTS) Since we cannot distinguish orphan...
Definition: txorphanage.h:21
Data structure to keep track of, and schedule, transaction downloads from peers.
Definition: txrequest.h:96
bool IsValid() const
Definition: validation.h:119
Result GetResult() const
Definition: validation.h:122
std::string ToString() const
Definition: validation.h:125
bool IsInvalid() const
Definition: validation.h:120
unsigned char * begin()
Definition: uint256.h:58
std::string ToString() const
Definition: uint256.cpp:64
bool IsNull() const
Definition: uint256.h:31
256-bit opaque blob.
Definition: uint256.h:124
@ BLOCK_CHECKPOINT
the block failed to meet one of our checkpoints
@ BLOCK_RECENT_CONSENSUS_CHANGE
Invalid by a change to consensus rules more recent than SegWit.
@ BLOCK_INVALID_HEADER
invalid proof of work or time too old
@ BLOCK_CACHED_INVALID
this block was cached as being invalid and we didn't store the reason why
@ BLOCK_CONSENSUS
invalid by consensus rules (excluding any below reasons)
@ BLOCK_MISSING_PREV
We don't have the previous block the checked one is built on.
@ BLOCK_INVALID_PREV
A block this one builds on is invalid.
@ BLOCK_MUTATED
the block's data didn't match the data committed to by the PoW
@ BLOCK_TIME_FUTURE
block timestamp was > 2 hours in the future (or our clock is bad)
@ BLOCK_RESULT_UNSET
initial value. Block has not yet been rejected
@ TX_MISSING_INPUTS
transaction was missing some of its inputs
@ TX_MEMPOOL_POLICY
violated mempool's fee/size/descendant/RBF/etc limits
@ TX_PREMATURE_SPEND
transaction spends a coinbase too early, or violates locktime/sequence locks
@ TX_INPUTS_NOT_STANDARD
inputs (covered by txid) failed policy rules
@ TX_WITNESS_STRIPPED
Transaction is missing a witness.
@ TX_CONFLICT
Tx already in mempool or conflicts with a tx in the chain (if it conflicts with another tx in mempool...
@ TX_RECENT_CONSENSUS_CHANGE
Invalid by a change to consensus rules more recent than SegWit.
@ TX_NOT_STANDARD
otherwise didn't meet our local policy rules
@ TX_WITNESS_MUTATED
Transaction might have a witness prior to SegWit activation, or witness may have been malleated (whic...
@ TX_RESULT_UNSET
initial value. Tx has not yet been rejected
@ TX_CONSENSUS
invalid by consensus rules
static size_t RecursiveDynamicUsage(const CScript &script)
Definition: core_memusage.h:12
static NodeId id
bool DeploymentActiveAt(const CBlockIndex &index, const Consensus::Params &params, Consensus::BuriedDeployment dep)
Determine if a deployment is active for this block.
if(na.IsAddrV1Compatible())
bool fLogIPs
Definition: logging.cpp:38
#define LogPrint(category,...)
Definition: logging.h:191
#define LogPrintf(...)
Definition: logging.h:187
unsigned int nonce
Definition: miner_tests.cpp:54
@ MEMPOOLREJ
Definition: logging.h:54
@ MEMPOOL
Definition: logging.h:40
@ NET
Definition: logging.h:38
@ DEPLOYMENT_SEGWIT
Definition: params.h:24
const char * FILTERLOAD
The filterload message tells the receiving peer to filter all relayed transactions and requested merk...
Definition: protocol.cpp:31
const char * CFHEADERS
cfheaders is a response to a getcfheaders request containing a filter header and a vector of filter h...
Definition: protocol.cpp:43
const char * CFILTER
cfilter is a response to a getcfilters request containing a single compact filter.
Definition: protocol.cpp:41
const char * BLOCK
The block message transmits a single serialized block.
Definition: protocol.cpp:25
const char * FILTERCLEAR
The filterclear message tells the receiving peer to remove a previously-set bloom filter.
Definition: protocol.cpp:33
const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
Definition: protocol.cpp:24
const char * ADDRV2
The addrv2 message relays connection information for peers on the network just like the addr message,...
Definition: protocol.cpp:16
const char * SENDHEADERS
Indicates that a node prefers to receive new block announcements via a "headers" message rather than ...
Definition: protocol.cpp:34
const char * PONG
The pong message replies to a ping message, proving to the pinging node that the ponging node is stil...
Definition: protocol.cpp:29
const char * SENDCMPCT
Contains a 1-byte bool and 8-byte LE version number.
Definition: protocol.cpp:36
const char * GETADDR
The getaddr message requests an addr message from the receiving node, preferably one with lots of IP ...
Definition: protocol.cpp:26
const char * GETCFCHECKPT
getcfcheckpt requests evenly spaced compact filter headers, enabling parallelized download and valida...
Definition: protocol.cpp:44
const char * NOTFOUND
The notfound message is a reply to a getdata message which requested an object the receiving node doe...
Definition: protocol.cpp:30
const char * CMPCTBLOCK
Contains a CBlockHeaderAndShortTxIDs object - providing a header and list of "short txids".
Definition: protocol.cpp:37
const char * MEMPOOL
The mempool message requests the TXIDs of transactions that the receiving node has verified as valid ...
Definition: protocol.cpp:27
const char * GETCFILTERS
getcfilters requests compact filters for a range of blocks.
Definition: protocol.cpp:40
const char * TX
The tx message transmits a single transaction.
Definition: protocol.cpp:23
const char * FILTERADD
The filteradd message tells the receiving peer to add a single element to a previously-set bloom filt...
Definition: protocol.cpp:32
const char * ADDR
The addr (IP address) message relays connection information for peers on the network.
Definition: protocol.cpp:15
const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
Definition: protocol.cpp:13
const char * GETBLOCKS
The getblocks message requests an inv message that provides block header hashes starting from a parti...
Definition: protocol.cpp:21
const char * FEEFILTER
The feefilter message tells the receiving peer not to inv us any txs which do not meet the specified ...
Definition: protocol.cpp:35
const char * GETHEADERS
The getheaders message requests a headers message that provides block headers starting from a particu...
Definition: protocol.cpp:22
const char * GETDATA
The getdata message requests one or more data objects from another node.
Definition: protocol.cpp:19
const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
Definition: protocol.cpp:14
const char * BLOCKTXN
Contains a BlockTransactions.
Definition: protocol.cpp:39
const char * GETCFHEADERS
getcfheaders requests a compact filter header and the filter hashes for a range of blocks,...
Definition: protocol.cpp:42
const char * SENDADDRV2
The sendaddrv2 message signals support for receiving ADDRV2 messages (BIP155).
Definition: protocol.cpp:17
const char * WTXIDRELAY
Indicates that a node prefers to relay transactions via wtxid, rather than txid.
Definition: protocol.cpp:46
const char * PING
The ping message is sent periodically to help confirm that the receiving peer is still connected.
Definition: protocol.cpp:28
const char * MERKLEBLOCK
The merkleblock message is a reply to a getdata message which requested a block using the inventory t...
Definition: protocol.cpp:20
const char * CFCHECKPT
cfcheckpt is a response to a getcfcheckpt request containing a vector of evenly spaced filter headers...
Definition: protocol.cpp:45
const char * GETBLOCKTXN
Contains a BlockTransactionsRequest Peer should respond with "blocktxn" message.
Definition: protocol.cpp:38
const char * INV
The inv message (inventory message) transmits one or more inventories of objects known to the transmi...
Definition: protocol.cpp:18
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
Definition: net.cpp:181
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:201
bool fListen
Definition: net.cpp:113
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:117
void CaptureMessage(const CAddress &addr, const std::string &msg_type, const Span< const unsigned char > &data, bool is_incoming)
Dump binary message to file, with timestamp.
Definition: net.cpp:3105
std::optional< CAddress > GetLocalAddrForPeer(CNode *pnode)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:208
bool IsReachable(enum Network net)
Definition: net.cpp:298
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:310
std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval)
Return a timestamp in the future (in microseconds) for exponentially distributed events.
Definition: net.cpp:3087
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:59
int64_t NodeId
Definition: net.h:87
static constexpr size_t MAX_ADDR_TO_SEND
The maximum number of address records permitted in an ADDR message.
static constexpr size_t MAX_ADDR_PROCESSING_TOKEN_BUCKET
The soft limit of the address processing token bucket (the regular MAX_ADDR_RATE_PER_SECOND based inc...
static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER
Number of blocks that can be requested at any given time from a single peer.
static constexpr auto AVG_FEEFILTER_BROADCAST_INTERVAL
Verify that INVENTORY_MAX_RECENT_RELAY is enough to cache everything typically relayed before uncondi...
static const unsigned int BLOCK_DOWNLOAD_WINDOW
Size of the "block download window": how far ahead of our current height do we fetch?...
static const int MAX_UNCONNECTING_HEADERS
Maximum number of unconnecting headers announcements before DoS score.
static constexpr int STALE_RELAY_AGE_LIMIT
Age after which a stale block will no longer be served if requested as protection against fingerprint...
static constexpr int HISTORICAL_BLOCK_AGE
Age after which a block is considered historical for purposes of rate limiting block relay.
static constexpr auto OUTBOUND_INVENTORY_BROADCAST_INTERVAL
Average delay between trickled inventory transmissions for outbound peers.
static constexpr auto RELAY_TX_CACHE_TIME
How long to cache transactions in mapRelay for normal relay.
static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS
Minimum blocks required to signal NODE_NETWORK_LIMITED.
static std::shared_ptr< const CBlock > most_recent_block GUARDED_BY(cs_most_recent_block)
static constexpr auto AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL
Average delay between local address broadcasts.
static const int MAX_BLOCKTXN_DEPTH
Maximum depth of blocks we're willing to respond to GETBLOCKTXN requests for.
static constexpr int32_t MAX_PEER_TX_REQUEST_IN_FLIGHT
Maximum number of in-flight transaction requests from a peer.
static constexpr auto OVERLOADED_PEER_TX_DELAY
How long to delay requesting transactions from overloaded peers (see MAX_PEER_TX_REQUEST_IN_FLIGHT).
static RecursiveMutex cs_most_recent_block
static constexpr int32_t MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT
Protect at least this many outbound peers from disconnection due to slow/ behind headers chain.
static constexpr std::chrono::microseconds GETDATA_TX_INTERVAL
How long to wait (in microseconds) before downloading a transaction from an additional peer.
static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL
Average delay between trickled inventory transmissions for inbound peers.
static constexpr auto BLOCK_STALLING_TIMEOUT
Time during which a peer must stall block download progress before being disconnected.
static uint32_t GetFetchFlags(const CNode &pfrom) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
static constexpr auto MAX_FEEFILTER_CHANGE_DELAY
Maximum feefilter broadcast delay after significant change.
static constexpr uint32_t MAX_GETCFILTERS_SIZE
Maximum number of compact filters that may be requested with one getcfilters.
static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_BASE
Headers download timeout.
static const unsigned int MAX_GETDATA_SZ
Limit to avoid sending big packets.
static constexpr int64_t STALE_CHECK_INTERVAL
How frequently to check for stale tips, in seconds.
void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds)
static constexpr std::chrono::minutes PING_INTERVAL
Time between pings automatically sent out for latency probing and keepalive.
static constexpr double BLOCK_DOWNLOAD_TIMEOUT_BASE
Block download timeout base, expressed in multiples of the block interval (i.e.
static constexpr int64_t MINIMUM_CONNECT_TIME
Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict,...
static constexpr unsigned int INVENTORY_MAX_RECENT_RELAY
The number of most recently announced transactions a peer can request.
static constexpr auto UNCONDITIONAL_RELAY_DELAY
How long a transaction has to be in the mempool before it can unconditionally be relayed (even when n...
static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL
Average delay between peer address broadcasts.
static constexpr int64_t EXTRA_PEER_CHECK_INTERVAL
How frequently to check for extra outbound peers and disconnect, in seconds.
static const unsigned int MAX_LOCATOR_SZ
The maximum number of entries in a locator.
static constexpr int32_t MAX_PEER_TX_ANNOUNCEMENTS
Maximum number of transactions to consider for requesting, per peer.
static constexpr auto TXID_RELAY_DELAY
How long to delay requesting transactions via txids, if we have wtxid-relaying peers.
static constexpr double BLOCK_DOWNLOAD_TIMEOUT_PER_PEER
Additional block download timeout per parallel downloading peer (i.e.
static constexpr double MAX_ADDR_RATE_PER_SECOND
The maximum rate of address records we're willing to process on average.
static const int MAX_CMPCTBLOCK_DEPTH
Maximum depth of blocks we're willing to serve as compact blocks to peers when requested.
static const unsigned int MAX_BLOCKS_TO_ANNOUNCE
Maximum number of headers to announce when relaying blocks with headers message.
static constexpr uint32_t MAX_GETCFHEADERS_SIZE
Maximum number of cf hashes that may be requested with one getcfheaders.
static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER
static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY
SHA256("main address relay")[0:8].
static constexpr unsigned int INVENTORY_BROADCAST_MAX
Maximum number of inventory items to send per transmission.
static const unsigned int MAX_HEADERS_RESULTS
Number of headers sent in one getheaders result.
static constexpr size_t MAX_PCT_ADDR_TO_SEND
the maximum percentage of addresses from our addrman to return in response to a getaddr message.
static const unsigned int MAX_INV_SZ
The maximum number of entries in an 'inv' protocol message.
static constexpr auto NONPREF_PEER_TX_DELAY
How long to delay requesting transactions from non-preferred peers.
static constexpr unsigned int INVENTORY_BROADCAST_PER_SECOND
Maximum rate of inventory items to send per second.
static constexpr int64_t CHAIN_SYNC_TIMEOUT
Timeout for (unprotected) outbound peers to sync to our chainwork, in seconds.
static const unsigned int DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
Default number of orphan+recently-replaced txn to keep around for block reconstruction.
static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS
Default for -maxorphantx, maximum number of orphan transactions kept in memory.
static const int DISCOURAGEMENT_THRESHOLD
Threshold for marking a node to be discouraged, e.g.
static constexpr int ADDRV2_FORMAT
A flag that is ORed into the protocol version to designate that addresses should be serialized in (un...
Definition: netaddress.h:34
bool IsProxy(const CNetAddr &addr)
Definition: netbase.cpp:647
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
Definition: policy.h:32
static const int SERIALIZE_TRANSACTION_NO_WITNESS
A flag that is ORed into the protocol version to designate that a transaction should be (un)serialize...
Definition: transaction.h:23
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:386
void SetServiceFlagsIBDCache(bool state)
Set the current IBD status in order to figure out the desirable service flags.
Definition: protocol.cpp:134
GenTxid ToGenTxid(const CInv &inv)
Convert a TX/WITNESS_TX/WTX CInv to a GenTxid.
Definition: protocol.cpp:223
ServiceFlags GetDesirableServiceFlags(ServiceFlags services)
Gets the set of service flags which are "desirable" for a given peer.
Definition: protocol.cpp:127
static bool HasAllDesirableServiceFlags(ServiceFlags services)
A shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services),...
Definition: protocol.h:343
const uint32_t MSG_WITNESS_FLAG
getdata message type flags
Definition: protocol.h:453
@ MSG_TX
Definition: protocol.h:462
@ MSG_WTX
Defined in BIP 339.
Definition: protocol.h:464
@ MSG_BLOCK
Definition: protocol.h:463
@ MSG_CMPCT_BLOCK
Defined in BIP152.
Definition: protocol.h:467
@ MSG_WITNESS_BLOCK
Defined in BIP144.
Definition: protocol.h:468
ServiceFlags
nServices flags
Definition: protocol.h:271
@ NODE_WITNESS
Definition: protocol.h:284
@ NODE_NETWORK_LIMITED
Definition: protocol.h:291
@ NODE_BLOOM
Definition: protocol.h:281
@ NODE_NETWORK
Definition: protocol.h:277
@ NODE_COMPACT_FILTERS
Definition: protocol.h:287
static bool MayHaveUsefulAddressDB(ServiceFlags services)
Checks if a peer with the given service flags may be capable of having a robust address-storage DB.
Definition: protocol.h:352
void GetRandBytes(unsigned char *buf, int num) noexcept
Overall design of the RNG and entropy sources.
Definition: random.cpp:584
constexpr auto GetRandMillis
Definition: random.h:84
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:231
reverse_range< T > reverse_iterate(T &x)
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:24
@ SER_NETWORK
Definition: serialize.h:138
#define LIMITED_STRING(obj, n)
Definition: serialize.h:445
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:282
constexpr Span< A > MakeSpan(A(&a)[N])
MakeSpan for arrays:
Definition: span.h:222
constexpr auto MakeUCharSpan(V &&v) -> decltype(UCharSpanCast(MakeSpan(std::forward< V >(v))))
Like MakeSpan, but for (const) unsigned char member types only.
Definition: span.h:249
std::vector< unsigned char > ParseHex(const char *psz)
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:87
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:115
std::vector< uint256 > vHave
Definition: block.h:116
bool IsNull() const
Definition: block.h:135
std::chrono::microseconds m_ping_wait
std::vector< int > vHeightInFlight
uint64_t m_addr_rate_limited
uint64_t m_addr_processed
std::vector< unsigned char > data
Definition: net.h:109
Parameters that influence chain consensus.
Definition: params.h:70
int64_t nPowTargetSpacing
Definition: params.h:103
Validation result for a single transaction mempool acceptance.
Definition: validation.h:149
const ResultType m_result_type
Definition: validation.h:155
const std::optional< std::list< CTransactionRef > > m_replaced_transactions
Mempool transactions replaced by the tx per BIP 125 rules.
Definition: validation.h:160
const TxValidationState m_state
Definition: validation.h:156
#define AssertLockNotHeld(cs)
Definition: sync.h:84
#define LOCK2(cs1, cs2)
Definition: sync.h:227
#define LOCK(cs)
Definition: sync.h:226
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:270
static int count
Definition: tests.c:41
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:48
int64_t GetTime()
DEPRECATED Use either GetTimeSeconds (not mockable) or GetTime<T> (mockable)
Definition: time.cpp:26
constexpr int64_t count_microseconds(std::chrono::microseconds t)
Definition: time.h:31
constexpr int64_t count_seconds(std::chrono::seconds t)
Helper to count the seconds of a duration.
Definition: time.h:29
double CountSecondsDouble(SecondsDouble t)
Helper to count the seconds in any std::chrono::duration type.
Definition: time.h:38
int64_t GetAdjustedTime()
Definition: timedata.cpp:35
void AddTimeData(const CNetAddr &ip, int64_t nOffsetSample)
Definition: timedata.cpp:42
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
#define TRACE6(context, event, a, b, c, d, e, f)
Definition: trace.h:34
RecursiveMutex g_cs_orphans
Guards orphan transactions and extra txs for compact blocks.
Definition: txorphanage.cpp:18
ArgsManager gArgs
Definition: system.cpp:85
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:131
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
Definition: validation.cpp:133
AssertLockHeld(pool.cs)
MempoolAcceptResult AcceptToMemoryPool(CChainState &active_chainstate, CTxMemPool &pool, const CTransactionRef &tx, bool bypass_limits, bool test_accept)
(Try to) add a transaction to the memory pool.
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.cpp:120
assert(!tx.IsCoinBase())
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
Definition: validation.h:79
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: validation.h:54
static const int WTXID_RELAY_VERSION
"wtxidrelay" command for wtxid-based relay starts with this version
Definition: version.h:39
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
Definition: version.h:15
static const int SHORT_IDS_BLOCKS_VERSION
short-id-based block download starts with this version
Definition: version.h:33
static const int SENDHEADERS_VERSION
"sendheaders" command and announcing blocks with headers starts with this version
Definition: version.h:27
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
static const int FEEFILTER_VERSION
"feefilter" tells peers to filter invs to you by fee starts with this version
Definition: version.h:30
static const int MIN_PEER_PROTO_VERSION
disconnect from peers older than this proto version
Definition: version.h:18
static const int INVALID_CB_NO_BAN_VERSION
not banning for invalid compact blocks starts with this version
Definition: version.h:36
static const int BIP0031_VERSION
BIP 0031, pong message, is enabled for all versions AFTER this one.
Definition: version.h:21