Skip to content

Commit 9181e2e

Browse files
committed
rpc: getblockfrompeer
1 parent 4ba67ce commit 9181e2e

File tree

8 files changed

+175
-0
lines changed

8 files changed

+175
-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;
@@ -1426,6 +1427,41 @@ bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex* pindex)
14261427
(GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, m_chainparams.GetConsensus()) < STALE_RELAY_AGE_LIMIT);
14271428
}
14281429

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

753+
static RPCHelpMan getblockfrompeer()
754+
{
755+
return RPCHelpMan{"getblockfrompeer",
756+
"\nAttempt to fetch block from a given peer.\n"
757+
"\nWe must have the header for this block, e.g. using submitheader.\n"
758+
"\nReturns {} if a block-request was successfully scheduled\n",
759+
{
760+
{"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The block hash"},
761+
{"nodeid", RPCArg::Type::NUM, RPCArg::Optional::NO, "The node ID (see getpeerinfo for node IDs)"},
762+
},
763+
RPCResult{RPCResult::Type::OBJ, "", "",
764+
{
765+
{RPCResult::Type::STR, "warnings", "any warnings"}
766+
}},
767+
RPCExamples{
768+
HelpExampleCli("getblockfrompeer", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
769+
+ HelpExampleRpc("getblockfrompeer", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
770+
},
771+
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
772+
{
773+
const NodeContext& node = EnsureAnyNodeContext(request.context);
774+
ChainstateManager& chainman = EnsureChainman(node);
775+
PeerManager& peerman = EnsurePeerman(node);
776+
777+
uint256 hash(ParseHashV(request.params[0], "hash"));
778+
779+
const NodeId nodeid = static_cast<NodeId>(request.params[1].get_int64());
780+
781+
const CBlockIndex* const index = WITH_LOCK(cs_main, return chainman.m_blockman.LookupBlockIndex(hash););
782+
783+
if (!index) {
784+
throw JSONRPCError(RPC_MISC_ERROR, "Block header missing");
785+
}
786+
787+
UniValue result = UniValue::VOBJ;
788+
789+
if (index->nStatus & BLOCK_HAVE_DATA) {
790+
result.pushKV("warnings", "Block already downloaded");
791+
} else if (!peerman.FetchBlock(nodeid, hash, *index)) {
792+
throw JSONRPCError(RPC_MISC_ERROR, "Failed to fetch block from peer");
793+
}
794+
return result;
795+
},
796+
};
797+
}
798+
751799
static RPCHelpMan getblockhash()
752800
{
753801
return RPCHelpMan{"getblockhash",
@@ -2586,6 +2634,7 @@ static const CRPCCommand commands[] =
25862634
{ "blockchain", &getbestblockhash, },
25872635
{ "blockchain", &getblockcount, },
25882636
{ "blockchain", &getblock, },
2637+
{ "blockchain", &getblockfrompeer, },
25892638
{ "blockchain", &getblockhash, },
25902639
{ "blockchain", &getblockheader, },
25912640
{ "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
@@ -3344,6 +3344,7 @@ bool CChainState::AcceptBlock(const std::shared_ptr<const CBlock>& pblock, Block
33443344
// This requires some new chain data structure to efficiently look up if a
33453345
// block is in a chain leading to a candidate for best tip, despite not
33463346
// being such a candidate itself.
3347+
// Note that this would break the getblockfrompeer RPC
33473348

33483349
// TODO: deal better with return value and error conditions for duplicate
33493350
// 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.nodes[0].generate(4)
31+
assert_equal(self.nodes[0].getblockcount(), 204)
32+
33+
self.log.info("Mine competing 3 blocks on Node 1")
34+
self.nodes[1].generate(3)
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, "Failed to fetch block from peer", 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
@@ -213,6 +213,7 @@
213213
'wallet_txn_clone.py --mineblock',
214214
'feature_notifications.py',
215215
'rpc_getblockfilter.py',
216+
'rpc_getblockfrompeer.py',
216217
'rpc_invalidateblock.py',
217218
'feature_utxo_set_hash.py',
218219
'feature_rbf.py',

0 commit comments

Comments
 (0)