Skip to content

Commit dce8c4c

Browse files
Sjorsjnewbery
andcommitted
rpc: getblockfrompeer
Co-authored-by: John Newbery <[email protected]>
1 parent b884aba commit dce8c4c

File tree

8 files changed

+181
-0
lines changed

8 files changed

+181
-0
lines changed

src/net_processing.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,7 @@ class PeerManagerImpl final : public PeerManager
312312
/** Implement PeerManager */
313313
void StartScheduledTasks(CScheduler& scheduler) override;
314314
void CheckForStaleTipAndEvictPeers() override;
315+
bool FetchBlock(NodeId id, const uint256& hash, const CBlockIndex& index) override;
315316
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) const override;
316317
bool IgnoresIncomingTxs() override { return m_ignore_incoming_txs; }
317318
void SendPings() override;
@@ -1427,6 +1428,41 @@ bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex* pindex)
14271428
(GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, m_chainparams.GetConsensus()) < STALE_RELAY_AGE_LIMIT);
14281429
}
14291430

1431+
bool PeerManagerImpl::FetchBlock(NodeId id, const uint256& hash, const CBlockIndex& index)
1432+
{
1433+
if (fImporting || fReindex) return false;
1434+
1435+
LOCK(cs_main);
1436+
// Ensure this peer exists and hasn't been disconnected
1437+
CNodeState* state = State(id);
1438+
if (state == nullptr) return false;
1439+
// Ignore pre-segwit peers
1440+
if (!state->fHaveWitness) return false;
1441+
1442+
// Mark block as in-flight unless it already is
1443+
if (!BlockRequested(id, index)) return false;
1444+
1445+
// Construct message to request the block
1446+
std::vector<CInv> invs{CInv(MSG_BLOCK | MSG_WITNESS_FLAG, hash)};
1447+
1448+
// Send block request message to the peer
1449+
bool success = m_connman.ForNode(id, [this, &invs](CNode* node) {
1450+
const CNetMsgMaker msgMaker(node->GetCommonVersion());
1451+
this->m_connman.PushMessage(node, msgMaker.Make(NetMsgType::GETDATA, invs));
1452+
return true;
1453+
});
1454+
1455+
if (success) {
1456+
LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
1457+
hash.ToString(), id);
1458+
} else {
1459+
RemoveBlockRequest(hash);
1460+
LogPrint(BCLog::NET, "Failed to request block %s from peer=%d\n",
1461+
hash.ToString(), id);
1462+
}
1463+
return success;
1464+
}
1465+
14301466
std::unique_ptr<PeerManager> PeerManager::make(const CChainParams& chainparams, CConnman& connman, AddrMan& addrman,
14311467
BanMan* banman, ChainstateManager& chainman,
14321468
CTxMemPool& pool, bool ignore_incoming_txs)

src/net_processing.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,16 @@ class PeerManager : public CValidationInterface, public NetEventsInterface
4242
CTxMemPool& pool, bool ignore_incoming_txs);
4343
virtual ~PeerManager() { }
4444

45+
/**
46+
* Attempt to manually fetch block from a given peer. We must already have the header.
47+
*
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
52+
*/
53+
virtual bool FetchBlock(NodeId id, const uint256& hash, const CBlockIndex& pindex) = 0;
54+
4555
/** Begin running background tasks, should only be called once */
4656
virtual void StartScheduledTasks(CScheduler& scheduler) = 0;
4757

src/rpc/blockchain.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
#include <hash.h>
1919
#include <index/blockfilterindex.h>
2020
#include <index/coinstatsindex.h>
21+
#include <net.h>
22+
#include <net_processing.h>
2123
#include <node/blockstorage.h>
2224
#include <node/coinstats.h>
2325
#include <node/context.h>
@@ -755,6 +757,58 @@ static RPCHelpMan getmempoolentry()
755757
};
756758
}
757759

760+
static RPCHelpMan getblockfrompeer()
761+
{
762+
return RPCHelpMan{"getblockfrompeer",
763+
"\nAttempt to fetch block from a given peer.\n"
764+
"\nWe must have the header for this block, e.g. using submitheader.\n"
765+
"\nReturns {} if a block-request was successfully scheduled\n",
766+
{
767+
{"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The block hash"},
768+
{"nodeid", RPCArg::Type::NUM, RPCArg::Optional::NO, "The node ID (see getpeerinfo for node IDs)"},
769+
},
770+
RPCResult{RPCResult::Type::OBJ, "", "",
771+
{
772+
{RPCResult::Type::STR, "warnings", "any warnings"}
773+
}},
774+
RPCExamples{
775+
HelpExampleCli("getblockfrompeer", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
776+
+ HelpExampleRpc("getblockfrompeer", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
777+
},
778+
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
779+
{
780+
const NodeContext& node = EnsureAnyNodeContext(request.context);
781+
ChainstateManager& chainman = EnsureChainman(node);
782+
PeerManager& peerman = EnsurePeerman(node);
783+
CConnman& connman = EnsureConnman(node);
784+
785+
uint256 hash(ParseHashV(request.params[0], "hash"));
786+
787+
const NodeId nodeid = static_cast<NodeId>(request.params[1].get_int64());
788+
789+
// Check that the peer with nodeid exists
790+
if (!connman.ForNode(nodeid, [](CNode* node) {return true;})) {
791+
throw JSONRPCError(RPC_MISC_ERROR, strprintf("Peer nodeid %d does not exist", nodeid));
792+
}
793+
794+
const CBlockIndex* const index = WITH_LOCK(cs_main, return chainman.m_blockman.LookupBlockIndex(hash););
795+
796+
if (!index) {
797+
throw JSONRPCError(RPC_MISC_ERROR, "Block header missing");
798+
}
799+
800+
UniValue result = UniValue::VOBJ;
801+
802+
if (index->nStatus & BLOCK_HAVE_DATA) {
803+
result.pushKV("warnings", "Block already downloaded");
804+
} else if (!peerman.FetchBlock(nodeid, hash, *index)) {
805+
throw JSONRPCError(RPC_MISC_ERROR, "Failed to fetch block from peer");
806+
}
807+
return result;
808+
},
809+
};
810+
}
811+
758812
static RPCHelpMan getblockhash()
759813
{
760814
return RPCHelpMan{"getblockhash",
@@ -2612,6 +2666,7 @@ static const CRPCCommand commands[] =
26122666
{ "blockchain", &getbestblockhash, },
26132667
{ "blockchain", &getblockcount, },
26142668
{ "blockchain", &getblock, },
2669+
{ "blockchain", &getblockfrompeer, },
26152670
{ "blockchain", &getblockhash, },
26162671
{ "blockchain", &getblockheader, },
26172672
{ "blockchain", &getchaintips, },

src/rpc/client.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ static const CRPCConvertParam vRPCConvertParams[] =
5656
{ "getbalance", 1, "minconf" },
5757
{ "getbalance", 2, "include_watchonly" },
5858
{ "getbalance", 3, "avoid_reuse" },
59+
{ "getblockfrompeer", 1, "nodeid" },
5960
{ "getblockhash", 0, "height" },
6061
{ "waitforblockheight", 0, "height" },
6162
{ "waitforblockheight", 1, "timeout" },

src/test/fuzz/rpc.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ const std::vector<std::string> RPC_COMMANDS_SAFE_FOR_FUZZING{
110110
"getblockfilter",
111111
"getblockhash",
112112
"getblockheader",
113+
"getblockfrompeer", // when no peers are connected, no p2p message is sent
113114
"getblockstats",
114115
"getblocktemplate",
115116
"getchaintips",

src/validation.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3408,6 +3408,7 @@ bool CChainState::AcceptBlock(const std::shared_ptr<const CBlock>& pblock, Block
34083408
// This requires some new chain data structure to efficiently look up if a
34093409
// block is in a chain leading to a candidate for best tip, despite not
34103410
// being such a candidate itself.
3411+
// Note that this would break the getblockfrompeer RPC
34113412

34123413
// TODO: deal better with return value and error conditions for duplicate
34133414
// and unrequested blocks.
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) 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+
"""Test the getblockfrompeer RPC."""
6+
7+
from test_framework.authproxy import JSONRPCException
8+
from test_framework.test_framework import BitcoinTestFramework
9+
from test_framework.util import (
10+
assert_equal,
11+
assert_raises_rpc_error,
12+
)
13+
14+
class GetBlockFromPeerTest(BitcoinTestFramework):
15+
def set_test_params(self):
16+
self.num_nodes = 2
17+
18+
def setup_network(self):
19+
self.setup_nodes()
20+
21+
def check_for_block(self, hash):
22+
try:
23+
self.nodes[0].getblock(hash)
24+
return True
25+
except JSONRPCException:
26+
return False
27+
28+
def run_test(self):
29+
self.log.info("Mine 4 blocks on Node 0")
30+
self.generate(self.nodes[0], 4, sync_fun=self.no_op)
31+
assert_equal(self.nodes[0].getblockcount(), 204)
32+
33+
self.log.info("Mine competing 3 blocks on Node 1")
34+
self.generate(self.nodes[1], 3, sync_fun=self.no_op)
35+
assert_equal(self.nodes[1].getblockcount(), 203)
36+
short_tip = self.nodes[1].getbestblockhash()
37+
38+
self.log.info("Connect nodes to sync headers")
39+
self.connect_nodes(0, 1)
40+
self.sync_blocks()
41+
42+
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")
49+
assert_raises_rpc_error(-1, "Block not found on disk", self.nodes[0].getblock, short_tip)
50+
51+
self.log.info("Fetch block from node 1")
52+
peers = self.nodes[0].getpeerinfo()
53+
assert_equal(len(peers), 1)
54+
peer_0_peer_1_id = peers[0]["id"]
55+
56+
self.log.info("Arguments must be sensible")
57+
assert_raises_rpc_error(-8, "hash must be of length 64 (not 4, for '1234')", self.nodes[0].getblockfrompeer, "1234", 0)
58+
59+
self.log.info("We must already have the header")
60+
assert_raises_rpc_error(-1, "Block header missing", self.nodes[0].getblockfrompeer, "00" * 32, 0)
61+
62+
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)
64+
65+
self.log.info("Successful fetch")
66+
result = self.nodes[0].getblockfrompeer(short_tip, peer_0_peer_1_id)
67+
self.wait_until(lambda: self.check_for_block(short_tip), timeout=1)
68+
assert(not "warnings" in result)
69+
70+
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")
74+
75+
if __name__ == '__main__':
76+
GetBlockFromPeerTest().main()

test/functional/test_runner.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,7 @@
215215
'wallet_txn_clone.py --mineblock',
216216
'feature_notifications.py',
217217
'rpc_getblockfilter.py',
218+
'rpc_getblockfrompeer.py',
218219
'rpc_invalidateblock.py',
219220
'feature_utxo_set_hash.py',
220221
'feature_rbf.py --legacy-wallet',

0 commit comments

Comments
 (0)