Skip to content

Commit 5c2aff8

Browse files
committed
Merge #10387: Eventually connect to NODE_NETWORK_LIMITED peers
eb91835 Add setter for g_initial_block_download_completed (Jonas Schnelli) 3f56df5 [QA] add NODE_NETWORK_LIMITED address relay and sync test (Jonas Schnelli) 158e1a6 [QA] fix mininode CAddress ser/deser (Jonas Schnelli) fa999af [QA] Allow addrman loopback tests (add debug option -addrmantest) (Jonas Schnelli) 6fe57bd Connect to peers signaling NODE_NETWORK_LIMITED when out-of-IBD (Jonas Schnelli) 31c45a9 Accept addresses with NODE_NETWORK_LIMITED flag (Jonas Schnelli) Pull request description: Eventually connect to peers signalling NODE_NETWORK_LIMITED if we are out of IBD. Accept and relay NODE_NETWORK_LIMITED peers in addrman. Tree-SHA512: 8a238fc97f767f81cae1866d6cc061390f23a72af4a711d2f7158c77f876017986abb371d213d1c84019eef7be4ca951e8e6f83fda36769c4e1a1d763f787037
2 parents 39dcac2 + eb91835 commit 5c2aff8

File tree

8 files changed

+119
-23
lines changed

8 files changed

+119
-23
lines changed

src/init.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,7 @@ std::string HelpMessage(HelpMessageMode mode)
448448
strUsage += HelpMessageOpt("-limitdescendantcount=<n>", strprintf("Do not accept transactions if any ancestor would have <n> or more in-mempool descendants (default: %u)", DEFAULT_DESCENDANT_LIMIT));
449449
strUsage += HelpMessageOpt("-limitdescendantsize=<n>", strprintf("Do not accept transactions if any ancestor would have more than <n> kilobytes of in-mempool descendants (default: %u).", DEFAULT_DESCENDANT_SIZE_LIMIT));
450450
strUsage += HelpMessageOpt("-vbparams=deployment:start:end", "Use given start/end times for specified version bits deployment (regtest-only)");
451+
strUsage += HelpMessageOpt("-addrmantest", "Allows to test address relay on localhost");
451452
}
452453
strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
453454
_("If <category> is not supplied or if <category> = 1, output all debugging information.") + " " + _("<category> can be:") + " " + ListLogCategories() + ".");

src/net.cpp

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,10 @@ void AdvertiseLocal(CNode *pnode)
181181
if (fListen && pnode->fSuccessfullyConnected)
182182
{
183183
CAddress addrLocal = GetLocalAddress(&pnode->addr, pnode->GetLocalServices());
184+
if (gArgs.GetBoolArg("-addrmantest", false)) {
185+
// use IPv4 loopback during addrmantest
186+
addrLocal = CAddress(CService(LookupNumeric("127.0.0.1", GetListenPort())), pnode->GetLocalServices());
187+
}
184188
// If discovery is enabled, sometimes give our peer the address it
185189
// tells us that it sees us as in case it has a better idea of our
186190
// address than we do.
@@ -189,7 +193,7 @@ void AdvertiseLocal(CNode *pnode)
189193
{
190194
addrLocal.SetIP(pnode->GetAddrLocal());
191195
}
192-
if (addrLocal.IsRoutable())
196+
if (addrLocal.IsRoutable() || gArgs.GetBoolArg("-addrmantest", false))
193197
{
194198
LogPrint(BCLog::NET, "AdvertiseLocal: advertising address %s\n", addrLocal.ToString());
195199
FastRandomContext insecure_rand;
@@ -2718,6 +2722,7 @@ CNode::CNode(NodeId idIn, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn
27182722
fOneShot = false;
27192723
m_manual_connection = false;
27202724
fClient = false; // set by version message
2725+
m_limited_node = false; // set by version message
27212726
fFeeler = false;
27222727
fSuccessfullyConnected = false;
27232728
fDisconnect = false;

src/net.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -641,6 +641,7 @@ class CNode
641641
bool fOneShot;
642642
bool m_manual_connection;
643643
bool fClient;
644+
bool m_limited_node; //after BIP159
644645
const bool fInbound;
645646
std::atomic_bool fSuccessfullyConnected;
646647
std::atomic_bool fDisconnect;

src/net_processing.cpp

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -892,6 +892,7 @@ void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex *pindexNew, const CB
892892
const int nNewHeight = pindexNew->nHeight;
893893
connman->SetBestHeight(nNewHeight);
894894

895+
SetServiceFlagsIBDCache(!fInitialDownload);
895896
if (!fInitialDownload) {
896897
// Find the hashes of all blocks that weren't previously in the best chain.
897898
std::vector<uint256> vHashes;
@@ -1642,7 +1643,13 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
16421643
pfrom->cleanSubVer = cleanSubVer;
16431644
}
16441645
pfrom->nStartingHeight = nStartingHeight;
1645-
pfrom->fClient = !(nServices & NODE_NETWORK);
1646+
1647+
// set nodes not relaying blocks and tx and not serving (parts) of the historical blockchain as "clients"
1648+
pfrom->fClient = (!(nServices & NODE_NETWORK) && !(nServices & NODE_NETWORK_LIMITED));
1649+
1650+
// set nodes not capable of serving the complete blockchain history as "limited nodes"
1651+
pfrom->m_limited_node = (!(nServices & NODE_NETWORK) && (nServices & NODE_NETWORK_LIMITED));
1652+
16461653
{
16471654
LOCK(pfrom->cs_filter);
16481655
pfrom->fRelayTxes = fRelay; // set to true after we get the first filter* message
@@ -1801,7 +1808,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
18011808
// We only bother storing full nodes, though this may include
18021809
// things which we would not make an outbound connection to, in
18031810
// part because we may make feeler connections to them.
1804-
if (!MayHaveUsefulAddressDB(addr.nServices))
1811+
if (!MayHaveUsefulAddressDB(addr.nServices) && !HasAllDesirableServiceFlags(addr.nServices))
18051812
continue;
18061813

18071814
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
@@ -3611,7 +3618,7 @@ bool PeerLogicValidation::SendMessages(CNode* pto, std::atomic<bool>& interruptM
36113618
// Message: getdata (blocks)
36123619
//
36133620
std::vector<CInv> vGetData;
3614-
if (!pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
3621+
if (!pto->fClient && ((fFetch && !pto->m_limited_node) || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
36153622
std::vector<const CBlockIndex*> vToDownload;
36163623
NodeId staller = -1;
36173624
FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller, consensusParams);

src/protocol.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
# include <arpa/inet.h>
1313
#endif
1414

15+
static std::atomic<bool> g_initial_block_download_completed(false);
16+
1517
namespace NetMsgType {
1618
const char *VERSION="version";
1719
const char *VERACK="verack";
@@ -127,6 +129,17 @@ bool CMessageHeader::IsValid(const MessageStartChars& pchMessageStartIn) const
127129
}
128130

129131

132+
ServiceFlags GetDesirableServiceFlags(ServiceFlags services) {
133+
if ((services & NODE_NETWORK_LIMITED) && g_initial_block_download_completed) {
134+
return ServiceFlags(NODE_NETWORK_LIMITED | NODE_WITNESS);
135+
}
136+
return ServiceFlags(NODE_NETWORK | NODE_WITNESS);
137+
}
138+
139+
void SetServiceFlagsIBDCache(bool state) {
140+
g_initial_block_download_completed = state;
141+
}
142+
130143

131144
CAddress::CAddress() : CService()
132145
{

src/protocol.h

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#include <uint256.h>
1616
#include <version.h>
1717

18+
#include <atomic>
1819
#include <stdint.h>
1920
#include <string>
2021

@@ -301,9 +302,10 @@ enum ServiceFlags : uint64_t {
301302
* If the NODE_NONE return value is changed, contrib/seeds/makeseeds.py
302303
* should be updated appropriately to filter for the same nodes.
303304
*/
304-
static ServiceFlags GetDesirableServiceFlags(ServiceFlags services) {
305-
return ServiceFlags(NODE_NETWORK | NODE_WITNESS);
306-
}
305+
ServiceFlags GetDesirableServiceFlags(ServiceFlags services);
306+
307+
/** Set the current IBD status in order to figure out the desirable service flags */
308+
void SetServiceFlagsIBDCache(bool status);
307309

308310
/**
309311
* A shortcut for (services & GetDesirableServiceFlags(services))
@@ -316,10 +318,10 @@ static inline bool HasAllDesirableServiceFlags(ServiceFlags services) {
316318

317319
/**
318320
* Checks if a peer with the given service flags may be capable of having a
319-
* robust address-storage DB. Currently an alias for checking NODE_NETWORK.
321+
* robust address-storage DB.
320322
*/
321323
static inline bool MayHaveUsefulAddressDB(ServiceFlags services) {
322-
return services & NODE_NETWORK;
324+
return (services & NODE_NETWORK) || (services & NODE_NETWORK_LIMITED);
323325
}
324326

325327
/** A CService with information about it as peer */

test/functional/p2p_node_network_limited.py

Lines changed: 70 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,21 @@
88
and that it responds to getdata requests for blocks correctly:
99
- send a block within 288 + 2 of the tip
1010
- disconnect peers who request blocks older than that."""
11-
from test_framework.messages import CInv, msg_getdata
12-
from test_framework.mininode import NODE_BLOOM, NODE_NETWORK_LIMITED, NODE_WITNESS, NetworkThread, P2PInterface
11+
from test_framework.messages import CInv, msg_getdata, msg_verack
12+
from test_framework.mininode import NODE_BLOOM, NODE_NETWORK_LIMITED, NODE_WITNESS, P2PInterface, wait_until, mininode_lock, network_thread_start, network_thread_join
1313
from test_framework.test_framework import BitcoinTestFramework
14-
from test_framework.util import assert_equal
14+
from test_framework.util import assert_equal, disconnect_nodes, connect_nodes_bi, sync_blocks
1515

1616
class P2PIgnoreInv(P2PInterface):
17+
firstAddrnServices = 0
1718
def on_inv(self, message):
1819
# The node will send us invs for other blocks. Ignore them.
1920
pass
20-
21+
def on_addr(self, message):
22+
self.firstAddrnServices = message.addrs[0].nServices
23+
def wait_for_addr(self, timeout=5):
24+
test_function = lambda: self.last_message.get("addr")
25+
wait_until(test_function, timeout=timeout, lock=mininode_lock)
2126
def send_getdata_for_block(self, blockhash):
2227
getdata_request = msg_getdata()
2328
getdata_request.inv.append(CInv(2, int(blockhash, 16)))
@@ -26,12 +31,24 @@ def send_getdata_for_block(self, blockhash):
2631
class NodeNetworkLimitedTest(BitcoinTestFramework):
2732
def set_test_params(self):
2833
self.setup_clean_chain = True
29-
self.num_nodes = 1
30-
self.extra_args = [['-prune=550']]
34+
self.num_nodes = 3
35+
self.extra_args = [['-prune=550', '-addrmantest'], [], []]
36+
37+
def disconnect_all(self):
38+
disconnect_nodes(self.nodes[0], 1)
39+
disconnect_nodes(self.nodes[1], 0)
40+
disconnect_nodes(self.nodes[2], 1)
41+
disconnect_nodes(self.nodes[2], 0)
42+
disconnect_nodes(self.nodes[0], 2)
43+
disconnect_nodes(self.nodes[1], 2)
44+
45+
def setup_network(self):
46+
super(NodeNetworkLimitedTest, self).setup_network()
47+
self.disconnect_all()
3148

3249
def run_test(self):
3350
node = self.nodes[0].add_p2p_connection(P2PIgnoreInv())
34-
NetworkThread().start()
51+
network_thread_start()
3552
node.wait_for_verack()
3653

3754
expected_services = NODE_BLOOM | NODE_WITNESS | NODE_NETWORK_LIMITED
@@ -43,7 +60,9 @@ def run_test(self):
4360
assert_equal(int(self.nodes[0].getnetworkinfo()['localservices'], 16), expected_services)
4461

4562
self.log.info("Mine enough blocks to reach the NODE_NETWORK_LIMITED range.")
46-
blocks = self.nodes[0].generate(292)
63+
connect_nodes_bi(self.nodes, 0, 1)
64+
blocks = self.nodes[1].generate(292)
65+
sync_blocks([self.nodes[0], self.nodes[1]])
4766

4867
self.log.info("Make sure we can max retrive block at tip-288.")
4968
node.send_getdata_for_block(blocks[1]) # last block in valid range
@@ -53,5 +72,48 @@ def run_test(self):
5372
node.send_getdata_for_block(blocks[0]) # first block outside of the 288+2 limit
5473
node.wait_for_disconnect(5)
5574

75+
self.log.info("Check local address relay, do a fresh connection.")
76+
self.nodes[0].disconnect_p2ps()
77+
network_thread_join()
78+
node1 = self.nodes[0].add_p2p_connection(P2PIgnoreInv())
79+
network_thread_start()
80+
node1.wait_for_verack()
81+
node1.send_message(msg_verack())
82+
83+
node1.wait_for_addr()
84+
#must relay address with NODE_NETWORK_LIMITED
85+
assert_equal(node1.firstAddrnServices, 1036)
86+
87+
self.nodes[0].disconnect_p2ps()
88+
node1.wait_for_disconnect()
89+
90+
# connect unsynced node 2 with pruned NODE_NETWORK_LIMITED peer
91+
# because node 2 is in IBD and node 0 is a NODE_NETWORK_LIMITED peer, sync must not be possible
92+
connect_nodes_bi(self.nodes, 0, 2)
93+
try:
94+
sync_blocks([self.nodes[0], self.nodes[2]], timeout=5)
95+
except:
96+
pass
97+
# node2 must remain at heigh 0
98+
assert_equal(self.nodes[2].getblockheader(self.nodes[2].getbestblockhash())['height'], 0)
99+
100+
# now connect also to node 1 (non pruned)
101+
connect_nodes_bi(self.nodes, 1, 2)
102+
103+
# sync must be possible
104+
sync_blocks(self.nodes)
105+
106+
# disconnect all peers
107+
self.disconnect_all()
108+
109+
# mine 10 blocks on node 0 (pruned node)
110+
self.nodes[0].generate(10)
111+
112+
# connect node1 (non pruned) with node0 (pruned) and check if the can sync
113+
connect_nodes_bi(self.nodes, 0, 1)
114+
115+
# sync must be possible, node 1 is no longer in IBD and should therefore connect to node 0 (NODE_NETWORK_LIMITED)
116+
sync_blocks([self.nodes[0], self.nodes[1]])
117+
56118
if __name__ == '__main__':
57119
NodeNetworkLimitedTest().main()

test/functional/test_framework/messages.py

100644100755
Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -186,19 +186,24 @@ def ToHex(obj):
186186

187187
class CAddress():
188188
def __init__(self):
189+
self.time = 0
189190
self.nServices = 1
190191
self.pchReserved = b"\x00" * 10 + b"\xff" * 2
191192
self.ip = "0.0.0.0"
192193
self.port = 0
193194

194-
def deserialize(self, f):
195+
def deserialize(self, f, with_time=True):
196+
if with_time:
197+
self.time = struct.unpack("<i", f.read(4))[0]
195198
self.nServices = struct.unpack("<Q", f.read(8))[0]
196199
self.pchReserved = f.read(12)
197200
self.ip = socket.inet_ntoa(f.read(4))
198201
self.port = struct.unpack(">H", f.read(2))[0]
199202

200-
def serialize(self):
203+
def serialize(self, with_time=True):
201204
r = b""
205+
if with_time:
206+
r += struct.pack("<i", self.time)
202207
r += struct.pack("<Q", self.nServices)
203208
r += self.pchReserved
204209
r += socket.inet_aton(self.ip)
@@ -856,11 +861,11 @@ def deserialize(self, f):
856861
self.nServices = struct.unpack("<Q", f.read(8))[0]
857862
self.nTime = struct.unpack("<q", f.read(8))[0]
858863
self.addrTo = CAddress()
859-
self.addrTo.deserialize(f)
864+
self.addrTo.deserialize(f, False)
860865

861866
if self.nVersion >= 106:
862867
self.addrFrom = CAddress()
863-
self.addrFrom.deserialize(f)
868+
self.addrFrom.deserialize(f, False)
864869
self.nNonce = struct.unpack("<Q", f.read(8))[0]
865870
self.strSubVer = deser_string(f)
866871
else:
@@ -888,8 +893,8 @@ def serialize(self):
888893
r += struct.pack("<i", self.nVersion)
889894
r += struct.pack("<Q", self.nServices)
890895
r += struct.pack("<q", self.nTime)
891-
r += self.addrTo.serialize()
892-
r += self.addrFrom.serialize()
896+
r += self.addrTo.serialize(False)
897+
r += self.addrFrom.serialize(False)
893898
r += struct.pack("<Q", self.nNonce)
894899
r += ser_string(self.strSubVer)
895900
r += struct.pack("<i", self.nStartingHeight)

0 commit comments

Comments
 (0)