Skip to content

Commit 39d9bbe

Browse files
author
MarcoFalke
committed
Merge bitcoin/bitcoin#23706: rpc: getblockfrompeer followups
923312f rpc: use peer_id, block_hash for FetchBlock (Sjors Provoost) 34d5399 rpc: more detailed errors for getblockfrompeer (Sjors Provoost) 60243ca rpc: turn already downloaded into error in getblockfrompeer (Sjors Provoost) 809d66b rpc: clarify getblockfrompeer behavior when called multiple times (Sjors Provoost) 0e3d7c5 refactor: drop redundant hash argument from FetchBlock (Sjors Provoost) 8d1a3e6 rpc: allow empty JSON object result (Sjors Provoost) bfbf91d test: fancier Python for getblockfrompeer (Sjors Provoost) Pull request description: Followups from #20295. ACKs for top commit: jonatack: ACK 923312f 📦 fjahr: tested ACK 923312f Tree-SHA512: da9eca76e302e249409c9d7f0d16cca668ed981e2ab6ca2d1743dad0d830b94b1bc5ffb9028a00764b863201945c273cc8f4409a4c9ca3817830007dffa2bc20
2 parents b94d0c7 + 923312f commit 39d9bbe

File tree

7 files changed

+48
-58
lines changed

7 files changed

+48
-58
lines changed

src/net_processing.cpp

+18-18
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,7 @@ class PeerManagerImpl final : public PeerManager
320320
/** Implement PeerManager */
321321
void StartScheduledTasks(CScheduler& scheduler) override;
322322
void CheckForStaleTipAndEvictPeers() override;
323-
bool FetchBlock(NodeId id, const uint256& hash, const CBlockIndex& index) override;
323+
std::optional<std::string> FetchBlock(NodeId peer_id, const CBlockIndex& block_index) override;
324324
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const override;
325325
bool IgnoresIncomingTxs() override { return m_ignore_incoming_txs; }
326326
void SendPings() override;
@@ -1460,39 +1460,39 @@ bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex* pindex)
14601460
(GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, m_chainparams.GetConsensus()) < STALE_RELAY_AGE_LIMIT);
14611461
}
14621462

1463-
bool PeerManagerImpl::FetchBlock(NodeId id, const uint256& hash, const CBlockIndex& index)
1463+
std::optional<std::string> PeerManagerImpl::FetchBlock(NodeId peer_id, const CBlockIndex& block_index)
14641464
{
1465-
if (fImporting || fReindex) return false;
1465+
if (fImporting) return "Importing...";
1466+
if (fReindex) return "Reindexing...";
14661467

14671468
LOCK(cs_main);
14681469
// Ensure this peer exists and hasn't been disconnected
1469-
CNodeState* state = State(id);
1470-
if (state == nullptr) return false;
1470+
CNodeState* state = State(peer_id);
1471+
if (state == nullptr) return "Peer does not exist";
14711472
// Ignore pre-segwit peers
1472-
if (!state->fHaveWitness) return false;
1473+
if (!state->fHaveWitness) return "Pre-SegWit peer";
14731474

1474-
// Mark block as in-flight unless it already is
1475-
if (!BlockRequested(id, index)) return false;
1475+
// Mark block as in-flight unless it already is (for this peer).
1476+
// If a block was already in-flight for a different peer, its BLOCKTXN
1477+
// response will be dropped.
1478+
if (!BlockRequested(peer_id, block_index)) return "Already requested from this peer";
14761479

14771480
// Construct message to request the block
1481+
const uint256& hash{block_index.GetBlockHash()};
14781482
std::vector<CInv> invs{CInv(MSG_BLOCK | MSG_WITNESS_FLAG, hash)};
14791483

14801484
// Send block request message to the peer
1481-
bool success = m_connman.ForNode(id, [this, &invs](CNode* node) {
1485+
bool success = m_connman.ForNode(peer_id, [this, &invs](CNode* node) {
14821486
const CNetMsgMaker msgMaker(node->GetCommonVersion());
14831487
this->m_connman.PushMessage(node, msgMaker.Make(NetMsgType::GETDATA, invs));
14841488
return true;
14851489
});
14861490

1487-
if (success) {
1488-
LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
1489-
hash.ToString(), id);
1490-
} else {
1491-
RemoveBlockRequest(hash);
1492-
LogPrint(BCLog::NET, "Failed to request block %s from peer=%d\n",
1493-
hash.ToString(), id);
1494-
}
1495-
return success;
1491+
if (!success) return "Peer not fully connected";
1492+
1493+
LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
1494+
hash.ToString(), peer_id);
1495+
return std::nullopt;
14961496
}
14971497

14981498
std::unique_ptr<PeerManager> PeerManager::make(const CChainParams& chainparams, CConnman& connman, AddrMan& addrman,

src/net_processing.h

+4-5
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,11 @@ class PeerManager : public CValidationInterface, public NetEventsInterface
4545
/**
4646
* Attempt to manually fetch block from a given peer. We must already have the header.
4747
*
48-
* @param[in] id The peer id
49-
* @param[in] hash The block hash
50-
* @param[in] pindex The blockindex
51-
* @returns Whether a request was successfully made
48+
* @param[in] peer_id The peer id
49+
* @param[in] block_index The blockindex
50+
* @returns std::nullopt if a request was successfully made, otherwise an error message
5251
*/
53-
virtual bool FetchBlock(NodeId id, const uint256& hash, const CBlockIndex& pindex) = 0;
52+
virtual std::optional<std::string> FetchBlock(NodeId peer_id, const CBlockIndex& block_index) = 0;
5453

5554
/** Begin running background tasks, should only be called once */
5655
virtual void StartScheduledTasks(CScheduler& scheduler) = 0;

src/rpc/blockchain.cpp

+14-23
Original file line numberDiff line numberDiff line change
@@ -792,15 +792,13 @@ static RPCHelpMan getblockfrompeer()
792792
"getblockfrompeer",
793793
"\nAttempt to fetch block from a given peer.\n"
794794
"\nWe must have the header for this block, e.g. using submitheader.\n"
795-
"\nReturns {} if a block-request was successfully scheduled\n",
795+
"Subsequent calls for the same block and a new peer will cause the response from the previous peer to be ignored.\n"
796+
"\nReturns an empty JSON object if the request was successfully scheduled.",
796797
{
797-
{"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The block hash"},
798-
{"nodeid", RPCArg::Type::NUM, RPCArg::Optional::NO, "The node ID (see getpeerinfo for node IDs)"},
798+
{"block_hash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The block hash to try to fetch"},
799+
{"peer_id", RPCArg::Type::NUM, RPCArg::Optional::NO, "The peer to fetch it from (see getpeerinfo for peer IDs)"},
799800
},
800-
RPCResult{RPCResult::Type::OBJ, "", "",
801-
{
802-
{RPCResult::Type::STR, "warnings", /*optional=*/true, "any warnings"},
803-
}},
801+
RPCResult{RPCResult::Type::OBJ_EMPTY, "", /*optional=*/ false, "", {}},
804802
RPCExamples{
805803
HelpExampleCli("getblockfrompeer", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
806804
+ HelpExampleRpc("getblockfrompeer", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
@@ -810,31 +808,24 @@ static RPCHelpMan getblockfrompeer()
810808
const NodeContext& node = EnsureAnyNodeContext(request.context);
811809
ChainstateManager& chainman = EnsureChainman(node);
812810
PeerManager& peerman = EnsurePeerman(node);
813-
CConnman& connman = EnsureConnman(node);
814-
815-
uint256 hash(ParseHashV(request.params[0], "hash"));
816-
817-
const NodeId nodeid = static_cast<NodeId>(request.params[1].get_int64());
818811

819-
// Check that the peer with nodeid exists
820-
if (!connman.ForNode(nodeid, [](CNode* node) {return true;})) {
821-
throw JSONRPCError(RPC_MISC_ERROR, strprintf("Peer nodeid %d does not exist", nodeid));
822-
}
812+
const uint256& block_hash{ParseHashV(request.params[0], "block_hash")};
813+
const NodeId peer_id{request.params[1].get_int64()};
823814

824-
const CBlockIndex* const index = WITH_LOCK(cs_main, return chainman.m_blockman.LookupBlockIndex(hash););
815+
const CBlockIndex* const index = WITH_LOCK(cs_main, return chainman.m_blockman.LookupBlockIndex(block_hash););
825816

826817
if (!index) {
827818
throw JSONRPCError(RPC_MISC_ERROR, "Block header missing");
828819
}
829820

830-
UniValue result = UniValue::VOBJ;
831-
832821
if (index->nStatus & BLOCK_HAVE_DATA) {
833-
result.pushKV("warnings", "Block already downloaded");
834-
} else if (!peerman.FetchBlock(nodeid, hash, *index)) {
835-
throw JSONRPCError(RPC_MISC_ERROR, "Failed to fetch block from peer");
822+
throw JSONRPCError(RPC_MISC_ERROR, "Block already downloaded");
836823
}
837-
return result;
824+
825+
if (const auto err{peerman.FetchBlock(peer_id, *index)}) {
826+
throw JSONRPCError(RPC_MISC_ERROR, err.value());
827+
}
828+
return UniValue::VOBJ;
838829
},
839830
};
840831
}

src/rpc/client.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ static const CRPCConvertParam vRPCConvertParams[] =
6060
{ "getbalance", 1, "minconf" },
6161
{ "getbalance", 2, "include_watchonly" },
6262
{ "getbalance", 3, "avoid_reuse" },
63-
{ "getblockfrompeer", 1, "nodeid" },
63+
{ "getblockfrompeer", 1, "peer_id" },
6464
{ "getblockhash", 0, "height" },
6565
{ "waitforblockheight", 0, "height" },
6666
{ "waitforblockheight", 1, "timeout" },

src/rpc/util.cpp

+5
Original file line numberDiff line numberDiff line change
@@ -830,6 +830,10 @@ void RPCResult::ToSections(Sections& sections, const OuterType outer_type, const
830830
return;
831831
}
832832
case Type::OBJ_DYN:
833+
case Type::OBJ_EMPTY: {
834+
sections.PushSection({indent + maybe_key + "{}", Description("empty JSON object")});
835+
return;
836+
}
833837
case Type::OBJ: {
834838
sections.PushSection({indent + maybe_key + "{", Description("json object")});
835839
for (const auto& i : m_inner) {
@@ -879,6 +883,7 @@ bool RPCResult::MatchesType(const UniValue& result) const
879883
return UniValue::VARR == result.getType();
880884
}
881885
case Type::OBJ_DYN:
886+
case Type::OBJ_EMPTY:
882887
case Type::OBJ: {
883888
return UniValue::VOBJ == result.getType();
884889
}

src/rpc/util.h

+1
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,7 @@ struct RPCResult {
240240
STR_AMOUNT, //!< Special string to represent a floating point amount
241241
STR_HEX, //!< Special string with only hex chars
242242
OBJ_DYN, //!< Special dictionary with keys that are not literals
243+
OBJ_EMPTY, //!< Special type to allow empty OBJ
243244
ARR_FIXED, //!< Special array that has a fixed number of entries
244245
NUM_TIME, //!< Special numeric to denote unix epoch time
245246
ELISION, //!< Special type to denote elision (...)

test/functional/rpc_getblockfrompeer.py

+5-11
Original file line numberDiff line numberDiff line change
@@ -40,12 +40,8 @@ def run_test(self):
4040
self.sync_blocks()
4141

4242
self.log.info("Node 0 should only have the header for node 1's block 3")
43-
for x in self.nodes[0].getchaintips():
44-
if x['hash'] == short_tip:
45-
assert_equal(x['status'], "headers-only")
46-
break
47-
else:
48-
raise AssertionError("short tip not synced")
43+
x = next(filter(lambda x: x['hash'] == short_tip, self.nodes[0].getchaintips()))
44+
assert_equal(x['status'], "headers-only")
4945
assert_raises_rpc_error(-1, "Block not found on disk", self.nodes[0].getblock, short_tip)
5046

5147
self.log.info("Fetch block from node 1")
@@ -60,17 +56,15 @@ def run_test(self):
6056
assert_raises_rpc_error(-1, "Block header missing", self.nodes[0].getblockfrompeer, "00" * 32, 0)
6157

6258
self.log.info("Non-existent peer generates error")
63-
assert_raises_rpc_error(-1, f"Peer nodeid {peer_0_peer_1_id + 1} does not exist", self.nodes[0].getblockfrompeer, short_tip, peer_0_peer_1_id + 1)
59+
assert_raises_rpc_error(-1, "Peer does not exist", self.nodes[0].getblockfrompeer, short_tip, peer_0_peer_1_id + 1)
6460

6561
self.log.info("Successful fetch")
6662
result = self.nodes[0].getblockfrompeer(short_tip, peer_0_peer_1_id)
6763
self.wait_until(lambda: self.check_for_block(short_tip), timeout=1)
68-
assert(not "warnings" in result)
64+
assert_equal(result, {})
6965

7066
self.log.info("Don't fetch blocks we already have")
71-
result = self.nodes[0].getblockfrompeer(short_tip, peer_0_peer_1_id)
72-
assert("warnings" in result)
73-
assert_equal(result["warnings"], "Block already downloaded")
67+
assert_raises_rpc_error(-1, "Block already downloaded", self.nodes[0].getblockfrompeer, short_tip, peer_0_peer_1_id)
7468

7569
if __name__ == '__main__':
7670
GetBlockFromPeerTest().main()

0 commit comments

Comments
 (0)