Skip to content

Commit e45fb7e

Browse files
author
MarcoFalke
committed
Merge #18877: Serve cfcheckpt requests
2308385 [test] Add test for cfcheckpt (Jim Posen) f9e00bb [net processing] Message handling for getcfcheckpt. (Jim Posen) 9ccaaba [init] Add -peerblockfilters option (Jim Posen) Pull request description: Serve cfcheckpt messages if basic block filter index is enabled and `-peercfilters` is set. `NODE_COMPACT_FILTERS` is not signaled to peers, but functionality can be used for testing and serving pre-configured clients. ACKs for top commit: jonatack: Code review re-ACK 2308385 the only change since my review @ 967e2b1 is an update required for #16224 that was merged yesterday. fjahr: re-ACK 2308385 jkczyz: re-ACK 2308385 ariard: re-Code Review ACK 2308385 clarkmoody: Tested ACK 2308385 MarcoFalke: re-ACK 2308385 🌳 theStack: ACK bitcoin/bitcoin@2308385 Tree-SHA512: 8c751bbd7d1c31a413096462ae025c3d2f3163c7016cbec472a5f5ec267f8dd19a2dfc4d749876d7409c1db546e6fdd16461c6863effcfa0d3e993edcfa92a08
2 parents 4fa3157 + 2308385 commit e45fb7e

File tree

9 files changed

+324
-0
lines changed

9 files changed

+324
-0
lines changed

src/init.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,7 @@ void SetupServerArgs(NodeContext& node)
446446
gArgs.AddArg("-onion=<ip:port>", "Use separate SOCKS5 proxy to reach peers via Tor hidden services, set -noonion to disable (default: -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
447447
gArgs.AddArg("-onlynet=<net>", "Make outgoing connections only through network <net> (ipv4, ipv6 or onion). Incoming connections are not affected by this option. This option can be specified multiple times to allow multiple networks.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
448448
gArgs.AddArg("-peerbloomfilters", strprintf("Support filtering of blocks and transaction with bloom filters (default: %u)", DEFAULT_PEERBLOOMFILTERS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
449+
gArgs.AddArg("-peerblockfilters", strprintf("Serve compact block filters to peers per BIP 157 (default: %u)", DEFAULT_PEERBLOCKFILTERS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
449450
gArgs.AddArg("-permitbaremultisig", strprintf("Relay non-P2SH multisig (default: %u)", DEFAULT_PERMIT_BAREMULTISIG), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
450451
gArgs.AddArg("-port=<port>", strprintf("Listen for connections on <port> (default: %u, testnet: %u, regtest: %u)", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort(), regtestChainParams->GetDefaultPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
451452
gArgs.AddArg("-proxy=<ip:port>", "Connect through SOCKS5 proxy, set -noproxy to disable (default: disabled)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
@@ -993,6 +994,13 @@ bool AppInitParameterInteraction()
993994
}
994995
}
995996

997+
// Basic filters are the only supported filters. The basic filters index must be enabled
998+
// to serve compact filters
999+
if (gArgs.GetBoolArg("-peerblockfilters", DEFAULT_PEERBLOCKFILTERS) &&
1000+
g_enabled_filter_types.count(BlockFilterType::BASIC) != 1) {
1001+
return InitError(_("Cannot set -peerblockfilters without -blockfilterindex."));
1002+
}
1003+
9961004
// if using block pruning, then disallow txindex
9971005
if (gArgs.GetArg("-prune", 0)) {
9981006
if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX))

src/net_processing.cpp

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,11 @@
88
#include <addrman.h>
99
#include <banman.h>
1010
#include <blockencodings.h>
11+
#include <blockfilter.h>
1112
#include <chainparams.h>
1213
#include <consensus/validation.h>
1314
#include <hash.h>
15+
#include <index/blockfilterindex.h>
1416
#include <validation.h>
1517
#include <merkleblock.h>
1618
#include <netmessagemaker.h>
@@ -127,6 +129,8 @@ static constexpr unsigned int INVENTORY_BROADCAST_MAX = 7 * INVENTORY_BROADCAST_
127129
static constexpr unsigned int AVG_FEEFILTER_BROADCAST_INTERVAL = 10 * 60;
128130
/** Maximum feefilter broadcast delay after significant change. */
129131
static constexpr unsigned int MAX_FEEFILTER_CHANGE_DELAY = 5 * 60;
132+
/** Interval between compact filter checkpoints. See BIP 157. */
133+
static constexpr int CFCHECKPT_INTERVAL = 1000;
130134

131135
struct COrphanTx {
132136
// When modifying, adapt the copy of this definition in tests/DoS_tests.
@@ -1969,6 +1973,107 @@ void static ProcessOrphanTx(CConnman* connman, CTxMemPool& mempool, std::set<uin
19691973
}
19701974
}
19711975

1976+
/**
1977+
* Validation logic for compact filters request handling.
1978+
*
1979+
* May disconnect from the peer in the case of a bad request.
1980+
*
1981+
* @param[in] pfrom The peer that we received the request from
1982+
* @param[in] chain_params Chain parameters
1983+
* @param[in] filter_type The filter type the request is for. Must be basic filters.
1984+
* @param[in] stop_hash The stop_hash for the request
1985+
* @param[out] stop_index The CBlockIndex for the stop_hash block, if the request can be serviced.
1986+
* @param[out] filter_index The filter index, if the request can be serviced.
1987+
* @return True if the request can be serviced.
1988+
*/
1989+
static bool PrepareBlockFilterRequest(CNode* pfrom, const CChainParams& chain_params,
1990+
BlockFilterType filter_type,
1991+
const uint256& stop_hash,
1992+
const CBlockIndex*& stop_index,
1993+
const BlockFilterIndex*& filter_index)
1994+
{
1995+
const bool supported_filter_type =
1996+
(filter_type == BlockFilterType::BASIC &&
1997+
gArgs.GetBoolArg("-peerblockfilters", DEFAULT_PEERBLOCKFILTERS));
1998+
if (!supported_filter_type) {
1999+
LogPrint(BCLog::NET, "peer %d requested unsupported block filter type: %d\n",
2000+
pfrom->GetId(), static_cast<uint8_t>(filter_type));
2001+
pfrom->fDisconnect = true;
2002+
return false;
2003+
}
2004+
2005+
{
2006+
LOCK(cs_main);
2007+
stop_index = LookupBlockIndex(stop_hash);
2008+
2009+
// Check that the stop block exists and the peer would be allowed to fetch it.
2010+
if (!stop_index || !BlockRequestAllowed(stop_index, chain_params.GetConsensus())) {
2011+
LogPrint(BCLog::NET, "peer %d requested invalid block hash: %s\n",
2012+
pfrom->GetId(), stop_hash.ToString());
2013+
pfrom->fDisconnect = true;
2014+
return false;
2015+
}
2016+
}
2017+
2018+
filter_index = GetBlockFilterIndex(filter_type);
2019+
if (!filter_index) {
2020+
LogPrint(BCLog::NET, "Filter index for supported type %s not found\n", BlockFilterTypeName(filter_type));
2021+
return false;
2022+
}
2023+
2024+
return true;
2025+
}
2026+
2027+
/**
2028+
* Handle a getcfcheckpt request.
2029+
*
2030+
* May disconnect from the peer in the case of a bad request.
2031+
*
2032+
* @param[in] pfrom The peer that we received the request from
2033+
* @param[in] vRecv The raw message received
2034+
* @param[in] chain_params Chain parameters
2035+
* @param[in] connman Pointer to the connection manager
2036+
*/
2037+
static void ProcessGetCFCheckPt(CNode* pfrom, CDataStream& vRecv, const CChainParams& chain_params,
2038+
CConnman* connman)
2039+
{
2040+
uint8_t filter_type_ser;
2041+
uint256 stop_hash;
2042+
2043+
vRecv >> filter_type_ser >> stop_hash;
2044+
2045+
const BlockFilterType filter_type = static_cast<BlockFilterType>(filter_type_ser);
2046+
2047+
const CBlockIndex* stop_index;
2048+
const BlockFilterIndex* filter_index;
2049+
if (!PrepareBlockFilterRequest(pfrom, chain_params, filter_type, stop_hash,
2050+
stop_index, filter_index)) {
2051+
return;
2052+
}
2053+
2054+
std::vector<uint256> headers(stop_index->nHeight / CFCHECKPT_INTERVAL);
2055+
2056+
// Populate headers.
2057+
const CBlockIndex* block_index = stop_index;
2058+
for (int i = headers.size() - 1; i >= 0; i--) {
2059+
int height = (i + 1) * CFCHECKPT_INTERVAL;
2060+
block_index = block_index->GetAncestor(height);
2061+
2062+
if (!filter_index->LookupFilterHeader(block_index, headers[i])) {
2063+
LogPrint(BCLog::NET, "Failed to find block filter header in index: filter_type=%s, block_hash=%s\n",
2064+
BlockFilterTypeName(filter_type), block_index->GetBlockHash().ToString());
2065+
return;
2066+
}
2067+
}
2068+
2069+
CSerializedNetMsg msg = CNetMsgMaker(pfrom->GetSendVersion())
2070+
.Make(NetMsgType::CFCHECKPT,
2071+
filter_type_ser,
2072+
stop_index->GetBlockHash(),
2073+
headers);
2074+
connman->PushMessage(pfrom, std::move(msg));
2075+
}
2076+
19722077
bool ProcessMessage(CNode* pfrom, const std::string& msg_type, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams, CTxMemPool& mempool, CConnman* connman, BanMan* banman, const std::atomic<bool>& interruptMsgProc)
19732078
{
19742079
LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(msg_type), vRecv.size(), pfrom->GetId());
@@ -3274,6 +3379,11 @@ bool ProcessMessage(CNode* pfrom, const std::string& msg_type, CDataStream& vRec
32743379
return true;
32753380
}
32763381

3382+
if (msg_type == NetMsgType::GETCFCHECKPT) {
3383+
ProcessGetCFCheckPt(pfrom, vRecv, chainparams, connman);
3384+
return true;
3385+
}
3386+
32773387
if (msg_type == NetMsgType::NOTFOUND) {
32783388
// Remove the NOTFOUND transactions from the peer
32793389
LOCK(cs_main);

src/net_processing.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 100;
2121
/** Default number of orphan+recently-replaced txn to keep around for block reconstruction */
2222
static const unsigned int DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN = 100;
2323
static const bool DEFAULT_PEERBLOOMFILTERS = false;
24+
static const bool DEFAULT_PEERBLOCKFILTERS = false;
2425

2526
class PeerLogicValidation final : public CValidationInterface, public NetEventsInterface {
2627
private:

src/protocol.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ const char *SENDCMPCT="sendcmpct";
4040
const char *CMPCTBLOCK="cmpctblock";
4141
const char *GETBLOCKTXN="getblocktxn";
4242
const char *BLOCKTXN="blocktxn";
43+
const char *GETCFCHECKPT="getcfcheckpt";
44+
const char *CFCHECKPT="cfcheckpt";
4345
} // namespace NetMsgType
4446

4547
/** All known message types. Keep this in the same order as the list of
@@ -71,6 +73,8 @@ const static std::string allNetMessageTypes[] = {
7173
NetMsgType::CMPCTBLOCK,
7274
NetMsgType::GETBLOCKTXN,
7375
NetMsgType::BLOCKTXN,
76+
NetMsgType::GETCFCHECKPT,
77+
NetMsgType::CFCHECKPT,
7478
};
7579
const static std::vector<std::string> allNetMessageTypesVec(allNetMessageTypes, allNetMessageTypes+ARRAYLEN(allNetMessageTypes));
7680

src/protocol.h

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,20 @@ extern const char *GETBLOCKTXN;
234234
* @since protocol version 70014 as described by BIP 152
235235
*/
236236
extern const char *BLOCKTXN;
237+
/**
238+
* getcfcheckpt requests evenly spaced compact filter headers, enabling
239+
* parallelized download and validation of the headers between them.
240+
* Only available with service bit NODE_COMPACT_FILTERS as described by
241+
* BIP 157 & 158.
242+
*/
243+
extern const char *GETCFCHECKPT;
244+
/**
245+
* cfcheckpt is a response to a getcfcheckpt request containing a vector of
246+
* evenly spaced filter headers for blocks on the requested chain.
247+
* Only available with service bit NODE_COMPACT_FILTERS as described by
248+
* BIP 157 & 158.
249+
*/
250+
extern const char *CFCHECKPT;
237251
};
238252

239253
/* Get a vector of all valid message types (see above) */

test/functional/p2p_blockfilters.py

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) 2019 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+
"""Tests NODE_COMPACT_FILTERS (BIP 157/158).
6+
7+
Tests that a node configured with -blockfilterindex and -peerblockfilters can serve
8+
cfcheckpts.
9+
"""
10+
11+
from test_framework.messages import (
12+
FILTER_TYPE_BASIC,
13+
msg_getcfcheckpt,
14+
)
15+
from test_framework.mininode import P2PInterface
16+
from test_framework.test_framework import BitcoinTestFramework
17+
from test_framework.util import (
18+
assert_equal,
19+
connect_nodes,
20+
disconnect_nodes,
21+
wait_until,
22+
)
23+
24+
class CompactFiltersTest(BitcoinTestFramework):
25+
def set_test_params(self):
26+
self.setup_clean_chain = True
27+
self.rpc_timeout = 480
28+
self.num_nodes = 2
29+
self.extra_args = [
30+
["-blockfilterindex", "-peerblockfilters"],
31+
["-blockfilterindex"],
32+
]
33+
34+
def run_test(self):
35+
# Node 0 supports COMPACT_FILTERS, node 1 does not.
36+
node0 = self.nodes[0].add_p2p_connection(P2PInterface())
37+
node1 = self.nodes[1].add_p2p_connection(P2PInterface())
38+
39+
# Nodes 0 & 1 share the same first 999 blocks in the chain.
40+
self.nodes[0].generate(999)
41+
self.sync_blocks(timeout=600)
42+
43+
# Stale blocks by disconnecting nodes 0 & 1, mining, then reconnecting
44+
disconnect_nodes(self.nodes[0], 1)
45+
46+
self.nodes[0].generate(1)
47+
wait_until(lambda: self.nodes[0].getblockcount() == 1000)
48+
stale_block_hash = self.nodes[0].getblockhash(1000)
49+
50+
self.nodes[1].generate(1001)
51+
wait_until(lambda: self.nodes[1].getblockcount() == 2000)
52+
53+
self.log.info("get cfcheckpt on chain to be re-orged out.")
54+
request = msg_getcfcheckpt(
55+
filter_type=FILTER_TYPE_BASIC,
56+
stop_hash=int(stale_block_hash, 16)
57+
)
58+
node0.send_and_ping(message=request)
59+
response = node0.last_message['cfcheckpt']
60+
assert_equal(response.filter_type, request.filter_type)
61+
assert_equal(response.stop_hash, request.stop_hash)
62+
assert_equal(len(response.headers), 1)
63+
64+
self.log.info("Reorg node 0 to a new chain.")
65+
connect_nodes(self.nodes[0], 1)
66+
self.sync_blocks(timeout=600)
67+
68+
main_block_hash = self.nodes[0].getblockhash(1000)
69+
assert main_block_hash != stale_block_hash, "node 0 chain did not reorganize"
70+
71+
self.log.info("Check that peers can fetch cfcheckpt on active chain.")
72+
tip_hash = self.nodes[0].getbestblockhash()
73+
request = msg_getcfcheckpt(
74+
filter_type=FILTER_TYPE_BASIC,
75+
stop_hash=int(tip_hash, 16)
76+
)
77+
node0.send_and_ping(request)
78+
response = node0.last_message['cfcheckpt']
79+
assert_equal(response.filter_type, request.filter_type)
80+
assert_equal(response.stop_hash, request.stop_hash)
81+
82+
main_cfcheckpt = self.nodes[0].getblockfilter(main_block_hash, 'basic')['header']
83+
tip_cfcheckpt = self.nodes[0].getblockfilter(tip_hash, 'basic')['header']
84+
assert_equal(
85+
response.headers,
86+
[int(header, 16) for header in (main_cfcheckpt, tip_cfcheckpt)]
87+
)
88+
89+
self.log.info("Check that peers can fetch cfcheckpt on stale chain.")
90+
request = msg_getcfcheckpt(
91+
filter_type=FILTER_TYPE_BASIC,
92+
stop_hash=int(stale_block_hash, 16)
93+
)
94+
node0.send_and_ping(request)
95+
response = node0.last_message['cfcheckpt']
96+
97+
stale_cfcheckpt = self.nodes[0].getblockfilter(stale_block_hash, 'basic')['header']
98+
assert_equal(
99+
response.headers,
100+
[int(header, 16) for header in (stale_cfcheckpt,)]
101+
)
102+
103+
self.log.info("Requests to node 1 without NODE_COMPACT_FILTERS results in disconnection.")
104+
requests = [
105+
msg_getcfcheckpt(
106+
filter_type=FILTER_TYPE_BASIC,
107+
stop_hash=int(main_block_hash, 16)
108+
),
109+
]
110+
for request in requests:
111+
node1 = self.nodes[1].add_p2p_connection(P2PInterface())
112+
node1.send_message(request)
113+
node1.wait_for_disconnect()
114+
115+
self.log.info("Check that invalid requests result in disconnection.")
116+
requests = [
117+
# Requesting unknown filter type results in disconnection.
118+
msg_getcfcheckpt(
119+
filter_type=255,
120+
stop_hash=int(main_block_hash, 16)
121+
),
122+
# Requesting unknown hash results in disconnection.
123+
msg_getcfcheckpt(
124+
filter_type=FILTER_TYPE_BASIC,
125+
stop_hash=123456789,
126+
),
127+
]
128+
for request in requests:
129+
node0 = self.nodes[0].add_p2p_connection(P2PInterface())
130+
node0.send_message(request)
131+
node0.wait_for_disconnect()
132+
133+
if __name__ == '__main__':
134+
CompactFiltersTest().main()

0 commit comments

Comments
 (0)