Skip to content

Commit c294457

Browse files
committed
merge bitcoin#20295: getblockfrompeer
1 parent 63ac87f commit c294457

23 files changed

+315
-115
lines changed

src/Makefile.am

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -287,12 +287,12 @@ BITCOIN_CORE_H = \
287287
rpc/blockchain.h \
288288
rpc/client.h \
289289
rpc/mining.h \
290-
rpc/net.h \
291290
rpc/protocol.h \
292291
rpc/rawtransaction_util.h \
293292
rpc/register.h \
294293
rpc/request.h \
295294
rpc/server.h \
295+
rpc/server_util.h \
296296
rpc/util.h \
297297
saltedhasher.h \
298298
scheduler.h \
@@ -510,6 +510,7 @@ libbitcoin_server_a_SOURCES = \
510510
rpc/quorums.cpp \
511511
rpc/rawtransaction.cpp \
512512
rpc/server.cpp \
513+
rpc/server_util.cpp \
513514
script/sigcache.cpp \
514515
shutdown.cpp \
515516
spork.cpp \

src/net_processing.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,7 @@ class PeerManagerImpl final : public PeerManager
398398

399399
/** Implement PeerManager */
400400
void CheckForStaleTipAndEvictPeers() override;
401+
bool FetchBlock(NodeId id, const uint256& hash, const CBlockIndex& index) override;
401402
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
402403
bool IgnoresIncomingTxs() override { return m_ignore_incoming_txs; }
403404
void SendPings() override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);;
@@ -1862,6 +1863,39 @@ bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex* pindex)
18621863
(GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, m_chainparams.GetConsensus()) < STALE_RELAY_AGE_LIMIT);
18631864
}
18641865

1866+
bool PeerManagerImpl::FetchBlock(NodeId id, const uint256& hash, const CBlockIndex& index)
1867+
{
1868+
if (fImporting || fReindex) return false;
1869+
1870+
LOCK(cs_main);
1871+
// Ensure this peer exists and hasn't been disconnected
1872+
CNodeState* state = State(id);
1873+
if (state == nullptr) return false;
1874+
1875+
// Mark block as in-flight unless it already is
1876+
if (!MarkBlockAsInFlight(id, index.GetBlockHash(), &index)) return false;
1877+
1878+
// Construct message to request the block
1879+
std::vector<CInv> invs{CInv(MSG_BLOCK, hash)};
1880+
1881+
// Send block request message to the peer
1882+
bool success = m_connman.ForNode(id, [this, &invs](CNode* node) {
1883+
const CNetMsgMaker msgMaker(node->GetCommonVersion());
1884+
this->m_connman.PushMessage(node, msgMaker.Make(NetMsgType::GETDATA, invs));
1885+
return true;
1886+
});
1887+
1888+
if (success) {
1889+
LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
1890+
hash.ToString(), id);
1891+
} else {
1892+
MarkBlockAsReceived(hash);
1893+
LogPrint(BCLog::NET, "Failed to request block %s from peer=%d\n",
1894+
hash.ToString(), id);
1895+
}
1896+
return success;
1897+
}
1898+
18651899
std::unique_ptr<PeerManager> PeerManager::make(const CChainParams& chainparams, CConnman& connman, AddrMan& addrman, BanMan* banman,
18661900
CScheduler &scheduler, ChainstateManager& chainman, CTxMemPool& pool,
18671901
CMasternodeMetaMan& mn_metaman, CMasternodeSync& mn_sync,

src/net_processing.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,16 @@ class PeerManager : public CValidationInterface, public NetEventsInterface
6666
const std::unique_ptr<LLMQContext>& llmq_ctx, bool ignore_incoming_txs);
6767
virtual ~PeerManager() { }
6868

69+
/**
70+
* Attempt to manually fetch block from a given peer. We must already have the header.
71+
*
72+
* @param[in] id The peer id
73+
* @param[in] hash The block hash
74+
* @param[in] pindex The blockindex
75+
* @returns Whether a request was successfully made
76+
*/
77+
virtual bool FetchBlock(NodeId id, const uint256& hash, const CBlockIndex& pindex) = 0;
78+
6979
/** Get statistics from node state */
7080
virtual bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const = 0;
7181

src/rest.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
#include <rpc/blockchain.h>
2020
#include <rpc/protocol.h>
2121
#include <rpc/server.h>
22+
#include <rpc/server_util.h>
2223
#include <streams.h>
2324
#include <sync.h>
2425
#include <txmempool.h>

src/rpc/blockchain.cpp

Lines changed: 56 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,16 @@
2222
#include <llmq/context.h>
2323
#include <node/blockstorage.h>
2424
#include <node/coinstats.h>
25+
#include <net.h>
26+
#include <net_processing.h>
2527
#include <node/context.h>
2628
#include <node/utxo_snapshot.h>
2729
#include <policy/feerate.h>
2830
#include <policy/fees.h>
2931
#include <policy/policy.h>
3032
#include <primitives/transaction.h>
3133
#include <rpc/server.h>
34+
#include <rpc/server_util.h>
3235
#include <rpc/util.h>
3336
#include <script/descriptor.h>
3437
#include <streams.h>
@@ -73,67 +76,6 @@ static CUpdatedBlock latestblock GUARDED_BY(cs_blockchange);
7376

7477
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, CTxMemPool& mempool, CChainState& active_chainstate, llmq::CChainLocksHandler& clhandler, llmq::CInstantSendManager& isman, UniValue& entry);
7578

76-
NodeContext& EnsureAnyNodeContext(const CoreContext& context)
77-
{
78-
auto* const node_context = GetContext<NodeContext>(context);
79-
if (!node_context) {
80-
throw JSONRPCError(RPC_INTERNAL_ERROR, "Node context not found");
81-
}
82-
return *node_context;
83-
}
84-
85-
CTxMemPool& EnsureMemPool(const NodeContext& node)
86-
{
87-
if (!node.mempool) {
88-
throw JSONRPCError(RPC_CLIENT_MEMPOOL_DISABLED, "Mempool disabled or instance not found");
89-
}
90-
return *node.mempool;
91-
}
92-
93-
CTxMemPool& EnsureAnyMemPool(const CoreContext& context)
94-
{
95-
return EnsureMemPool(EnsureAnyNodeContext(context));
96-
}
97-
98-
ChainstateManager& EnsureChainman(const NodeContext& node)
99-
{
100-
if (!node.chainman) {
101-
throw JSONRPCError(RPC_INTERNAL_ERROR, "Node chainman not found");
102-
}
103-
return *node.chainman;
104-
}
105-
106-
ChainstateManager& EnsureAnyChainman(const CoreContext& context)
107-
{
108-
return EnsureChainman(EnsureAnyNodeContext(context));
109-
}
110-
111-
CBlockPolicyEstimator& EnsureFeeEstimator(const NodeContext& node)
112-
{
113-
if (!node.fee_estimator) {
114-
throw JSONRPCError(RPC_INTERNAL_ERROR, "Fee estimation disabled");
115-
}
116-
return *node.fee_estimator;
117-
}
118-
119-
CBlockPolicyEstimator& EnsureAnyFeeEstimator(const CoreContext& context)
120-
{
121-
return EnsureFeeEstimator(EnsureAnyNodeContext(context));
122-
}
123-
124-
LLMQContext& EnsureLLMQContext(const NodeContext& node)
125-
{
126-
if (!node.llmq_ctx) {
127-
throw JSONRPCError(RPC_INTERNAL_ERROR, "Node LLMQ context not found");
128-
}
129-
return *node.llmq_ctx;
130-
}
131-
132-
LLMQContext& EnsureAnyLLMQContext(const CoreContext& context)
133-
{
134-
return EnsureLLMQContext(EnsureAnyNodeContext(context));
135-
}
136-
13779
/* Calculate the difficulty for a given block index.
13880
*/
13981
double GetDifficulty(const CBlockIndex* blockindex)
@@ -825,6 +767,58 @@ static RPCHelpMan getmempoolentry()
825767
};
826768
}
827769

770+
static RPCHelpMan getblockfrompeer()
771+
{
772+
return RPCHelpMan{"getblockfrompeer",
773+
"\nAttempt to fetch block from a given peer.\n"
774+
"\nWe must have the header for this block, e.g. using submitheader.\n"
775+
"\nReturns {} if a block-request was successfully scheduled\n",
776+
{
777+
{"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The block hash"},
778+
{"nodeid", RPCArg::Type::NUM, RPCArg::Optional::NO, "The node ID (see getpeerinfo for node IDs)"},
779+
},
780+
RPCResult{RPCResult::Type::OBJ, "", "",
781+
{
782+
{RPCResult::Type::STR, "warnings", "any warnings"}
783+
}},
784+
RPCExamples{
785+
HelpExampleCli("getblockfrompeer", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
786+
+ HelpExampleRpc("getblockfrompeer", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
787+
},
788+
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
789+
{
790+
const NodeContext& node = EnsureAnyNodeContext(request.context);
791+
ChainstateManager& chainman = EnsureChainman(node);
792+
PeerManager& peerman = EnsurePeerman(node);
793+
CConnman& connman = EnsureConnman(node);
794+
795+
uint256 hash(ParseHashV(request.params[0], "hash"));
796+
797+
const NodeId nodeid = static_cast<NodeId>(request.params[1].get_int64());
798+
799+
// Check that the peer with nodeid exists
800+
if (!connman.ForNode(nodeid, [](CNode* node) {return true;})) {
801+
throw JSONRPCError(RPC_MISC_ERROR, strprintf("Peer nodeid %d does not exist", nodeid));
802+
}
803+
804+
const CBlockIndex* const index = WITH_LOCK(cs_main, return chainman.m_blockman.LookupBlockIndex(hash););
805+
806+
if (!index) {
807+
throw JSONRPCError(RPC_MISC_ERROR, "Block header missing");
808+
}
809+
810+
UniValue result = UniValue::VOBJ;
811+
812+
if (index->nStatus & BLOCK_HAVE_DATA) {
813+
result.pushKV("warnings", "Block already downloaded");
814+
} else if (!peerman.FetchBlock(nodeid, hash, *index)) {
815+
throw JSONRPCError(RPC_MISC_ERROR, "Failed to fetch block from peer");
816+
}
817+
return result;
818+
},
819+
};
820+
}
821+
828822
static RPCHelpMan getblockhashes()
829823
{
830824
return RPCHelpMan{"getblockhashes",
@@ -3058,6 +3052,7 @@ static const CRPCCommand commands[] =
30583052
{ "blockchain", "getbestchainlock", &getbestchainlock, {} },
30593053
{ "blockchain", "getblockcount", &getblockcount, {} },
30603054
{ "blockchain", "getblock", &getblock, {"blockhash","verbosity|verbose"} },
3055+
{ "blockchain", "getblockfrompeer", &getblockfrompeer, {"blockhash", "nodeid"}},
30613056
{ "blockchain", "getblockhashes", &getblockhashes, {"high","low"} },
30623057
{ "blockchain", "getblockhash", &getblockhash, {"height"} },
30633058
{ "blockchain", "getblockheader", &getblockheader, {"blockhash","verbose"} },

src/rpc/blockchain.h

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
#define BITCOIN_RPC_BLOCKCHAIN_H
77

88
#include <amount.h>
9-
#include <context.h>
109
#include <core_io.h>
1110
#include <streams.h>
1211
#include <sync.h>
@@ -18,12 +17,9 @@ extern RecursiveMutex cs_main;
1817

1918
class CBlock;
2019
class CBlockIndex;
21-
class CBlockPolicyEstimator;
2220
class CChainState;
2321
class CTxMemPool;
24-
class ChainstateManager;
2522
class UniValue;
26-
struct LLMQContext;
2723
struct NodeContext;
2824
namespace llmq {
2925
class CChainLocksHandler;
@@ -61,16 +57,6 @@ void CalculatePercentilesBySize(CAmount result[NUM_GETBLOCKSTATS_PERCENTILES], s
6157
void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
6258
void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex = true, const CTxUndo* txundo = nullptr, const CSpentIndexTxInfo* ptxSpentInfo = nullptr);
6359

64-
NodeContext& EnsureAnyNodeContext(const CoreContext& context);
65-
CTxMemPool& EnsureMemPool(const NodeContext& node);
66-
CTxMemPool& EnsureAnyMemPool(const CoreContext& context);
67-
ChainstateManager& EnsureChainman(const NodeContext& node);
68-
ChainstateManager& EnsureAnyChainman(const CoreContext& context);
69-
CBlockPolicyEstimator& EnsureFeeEstimator(const NodeContext& node);
70-
CBlockPolicyEstimator& EnsureAnyFeeEstimator(const CoreContext& context);
71-
LLMQContext& EnsureLLMQContext(const NodeContext& node);
72-
LLMQContext& EnsureAnyLLMQContext(const CoreContext& context);
73-
7460
/**
7561
* Helper to create UTXO snapshots given a chainstate and a file handle.
7662
* @return a UniValue map containing metadata about the snapshot.

src/rpc/client.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ static const CRPCConvertParam vRPCConvertParams[] =
6666
{ "getbalance", 2, "addlocked" },
6767
{ "getbalance", 3, "include_watchonly" },
6868
{ "getbalance", 4, "avoid_reuse" },
69+
{ "getblockfrompeer", 1, "nodeid" },
6970
{ "getchaintips", 0, "count" },
7071
{ "getchaintips", 1, "branchlen" },
7172
{ "getblockhash", 0, "height" },

src/rpc/coinjoin.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
#include <coinjoin/context.h>
88
#include <coinjoin/server.h>
99
#include <rpc/blockchain.h>
10-
#include <rpc/net.h>
1110
#include <rpc/server.h>
11+
#include <rpc/server_util.h>
1212
#include <rpc/util.h>
1313
#include <util/strencodings.h>
1414

src/rpc/evo.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
#include <node/context.h>
2525
#include <rpc/blockchain.h>
2626
#include <rpc/server.h>
27+
#include <rpc/server_util.h>
2728
#include <rpc/util.h>
2829
#include <util/moneystr.h>
2930
#include <util/translation.h>

src/rpc/governance.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@
1616
#include <node/context.h>
1717
#include <net.h>
1818
#include <rpc/blockchain.h>
19-
#include <rpc/net.h>
2019
#include <rpc/server.h>
20+
#include <rpc/server_util.h>
2121
#include <rpc/util.h>
2222
#include <governance/common.h>
2323
#include <util/strencodings.h>

src/rpc/masternode.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@
1515
#include <net.h>
1616
#include <netbase.h>
1717
#include <rpc/blockchain.h>
18-
#include <rpc/net.h>
1918
#include <rpc/server.h>
19+
#include <rpc/server_util.h>
2020
#include <rpc/util.h>
2121
#include <univalue.h>
2222
#include <util/strencodings.h>

src/rpc/mining.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@
2626
#include <pow.h>
2727
#include <rpc/blockchain.h>
2828
#include <rpc/mining.h>
29-
#include <rpc/net.h>
3029
#include <rpc/server.h>
30+
#include <rpc/server_util.h>
3131
#include <rpc/util.h>
3232
#include <script/descriptor.h>
3333
#include <script/script.h>

src/rpc/misc.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919
#include <net.h>
2020
#include <node/context.h>
2121
#include <rpc/blockchain.h>
22-
#include <rpc/net.h>
2322
#include <rpc/server.h>
23+
#include <rpc/server_util.h>
2424
#include <rpc/util.h>
2525
#include <scheduler.h>
2626
#include <script/descriptor.h>

src/rpc/net.cpp

Lines changed: 1 addition & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
#include <chainparams.h>
1010
#include <clientversion.h>
1111
#include <core_io.h>
12-
#include <net.h>
1312
#include <net_permissions.h>
1413
#include <net_processing.h>
1514
#include <net_types.h> // For banmap_t
@@ -18,12 +17,12 @@
1817
#include <policy/settings.h>
1918
#include <rpc/blockchain.h>
2019
#include <rpc/protocol.h>
20+
#include <rpc/server_util.h>
2121
#include <rpc/util.h>
2222
#include <sync.h>
2323
#include <timedata.h>
2424
#include <util/strencodings.h>
2525
#include <util/string.h>
26-
#include <util/system.h>
2726
#include <util/translation.h>
2827
#include <validation.h>
2928
#include <version.h>
@@ -40,22 +39,6 @@ const std::vector<std::string> CONNECTION_TYPE_DOC{
4039
"feeler (short-lived automatic connection for testing addresses)"
4140
};
4241

43-
CConnman& EnsureConnman(const NodeContext& node)
44-
{
45-
if (!node.connman) {
46-
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
47-
}
48-
return *node.connman;
49-
}
50-
51-
PeerManager& EnsurePeerman(const NodeContext& node)
52-
{
53-
if (!node.peerman) {
54-
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
55-
}
56-
return *node.peerman;
57-
}
58-
5942
static RPCHelpMan getconnectioncount()
6043
{
6144
return RPCHelpMan{"getconnectioncount",

0 commit comments

Comments
 (0)