Skip to content

Commit

Permalink
Merge bitcoin/bitcoin#25962: net: Add CNodeOptions and increase const…
Browse files Browse the repository at this point in the history
…ness

377e9cc scripted-diff: net: rename permissionFlags to permission_flags (Anthony Towns)
0a7fc42 net: make CNode::m_prefer_evict const (Anthony Towns)
d394156 net: make CNode::m_permissionFlags const (Anthony Towns)
9dccc33 net: add CNodeOptions for optional CNode constructor params (Anthony Towns)

Pull request description:

  Adds CNodeOptions to make it easier to add optional parameters to the CNode constructor, and makes prefer_evict and m_permissionFlags actually const.

ACKs for top commit:
  naumenkogs:
    ACK 377e9cc
  jonatack:
    ACK 377e9cc per `git range-diff 52dcb1d 2f3602b 377e9cc`
  vasild:
    ACK 377e9cc
  ryanofsky:
    Code review ACK 377e9cc. Looks good and feel free to ignore suggestions!

Tree-SHA512: 06fd6748770bad75ec8c966fdb73b7534c10bd61838f6f1b36b3f3d6a438e58f6a7d0edb011977e5c118ed7ea85325fac35e10dde520fef249f7a780cf500a85
  • Loading branch information
MacroFake committed Sep 2, 2022
2 parents 7281fac + 377e9cc commit ea67232
Show file tree
Hide file tree
Showing 9 changed files with 47 additions and 38 deletions.
46 changes: 25 additions & 21 deletions src/net.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,7 @@ CNode* CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCo
pszDest ? pszDest : "",
conn_type,
/*inbound_onion=*/false,
std::move(i2p_transient_session));
CNodeOptions{ .i2p_sam_session = std::move(i2p_transient_session) });
pnode->AddRef();

// We're making a new connection, harvest entropy from the time (and our peer count)
Expand Down Expand Up @@ -637,7 +637,7 @@ void CNode::CopyStats(CNodeStats& stats)
X(mapRecvBytesPerMsgType);
X(nRecvBytes);
}
X(m_permissionFlags);
X(m_permission_flags);

X(m_last_ping_time);
X(m_min_ping_time);
Expand Down Expand Up @@ -936,27 +936,27 @@ void CConnman::AcceptConnection(const ListenSocket& hListenSocket) {

const CAddress addr_bind{MaybeFlipIPv6toCJDNS(GetBindAddress(*sock)), NODE_NONE};

NetPermissionFlags permissionFlags = NetPermissionFlags::None;
hListenSocket.AddSocketPermissionFlags(permissionFlags);
NetPermissionFlags permission_flags = NetPermissionFlags::None;
hListenSocket.AddSocketPermissionFlags(permission_flags);

CreateNodeFromAcceptedSocket(std::move(sock), permissionFlags, addr_bind, addr);
CreateNodeFromAcceptedSocket(std::move(sock), permission_flags, addr_bind, addr);
}

void CConnman::CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
NetPermissionFlags permissionFlags,
NetPermissionFlags permission_flags,
const CAddress& addr_bind,
const CAddress& addr)
{
int nInbound = 0;
int nMaxInbound = nMaxConnections - m_max_outbound;

AddWhitelistPermissionFlags(permissionFlags, addr);
if (NetPermissions::HasFlag(permissionFlags, NetPermissionFlags::Implicit)) {
NetPermissions::ClearFlag(permissionFlags, NetPermissionFlags::Implicit);
if (gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) NetPermissions::AddFlag(permissionFlags, NetPermissionFlags::ForceRelay);
if (gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)) NetPermissions::AddFlag(permissionFlags, NetPermissionFlags::Relay);
NetPermissions::AddFlag(permissionFlags, NetPermissionFlags::Mempool);
NetPermissions::AddFlag(permissionFlags, NetPermissionFlags::NoBan);
AddWhitelistPermissionFlags(permission_flags, addr);
if (NetPermissions::HasFlag(permission_flags, NetPermissionFlags::Implicit)) {
NetPermissions::ClearFlag(permission_flags, NetPermissionFlags::Implicit);
if (gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) NetPermissions::AddFlag(permission_flags, NetPermissionFlags::ForceRelay);
if (gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)) NetPermissions::AddFlag(permission_flags, NetPermissionFlags::Relay);
NetPermissions::AddFlag(permission_flags, NetPermissionFlags::Mempool);
NetPermissions::AddFlag(permission_flags, NetPermissionFlags::NoBan);
}

{
Expand Down Expand Up @@ -987,15 +987,15 @@ void CConnman::CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,

// Don't accept connections from banned peers.
bool banned = m_banman && m_banman->IsBanned(addr);
if (!NetPermissions::HasFlag(permissionFlags, NetPermissionFlags::NoBan) && banned)
if (!NetPermissions::HasFlag(permission_flags, NetPermissionFlags::NoBan) && banned)
{
LogPrint(BCLog::NET, "connection from %s dropped (banned)\n", addr.ToString());
return;
}

// Only accept connections from discouraged peers if our inbound slots aren't (almost) full.
bool discouraged = m_banman && m_banman->IsDiscouraged(addr);
if (!NetPermissions::HasFlag(permissionFlags, NetPermissionFlags::NoBan) && nInbound + 1 >= nMaxInbound && discouraged)
if (!NetPermissions::HasFlag(permission_flags, NetPermissionFlags::NoBan) && nInbound + 1 >= nMaxInbound && discouraged)
{
LogPrint(BCLog::NET, "connection from %s dropped (discouraged)\n", addr.ToString());
return;
Expand All @@ -1014,7 +1014,7 @@ void CConnman::CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize();

ServiceFlags nodeServices = nLocalServices;
if (NetPermissions::HasFlag(permissionFlags, NetPermissionFlags::BloomFilter)) {
if (NetPermissions::HasFlag(permission_flags, NetPermissionFlags::BloomFilter)) {
nodeServices = static_cast<ServiceFlags>(nodeServices | NODE_BLOOM);
}

Expand All @@ -1027,10 +1027,12 @@ void CConnman::CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
addr_bind,
/*addrNameIn=*/"",
ConnectionType::INBOUND,
inbound_onion);
inbound_onion,
CNodeOptions{
.permission_flags = permission_flags,
.prefer_evict = discouraged,
});
pnode->AddRef();
pnode->m_permissionFlags = permissionFlags;
pnode->m_prefer_evict = discouraged;
m_msgproc->InitializeNode(*pnode, nodeServices);

LogPrint(BCLog::NET, "connection from %s accepted\n", addr.ToString());
Expand Down Expand Up @@ -2722,20 +2724,22 @@ CNode::CNode(NodeId idIn,
const std::string& addrNameIn,
ConnectionType conn_type_in,
bool inbound_onion,
std::unique_ptr<i2p::sam::Session>&& i2p_sam_session)
CNodeOptions&& node_opts)
: m_deserializer{std::make_unique<V1TransportDeserializer>(V1TransportDeserializer(Params(), idIn, SER_NETWORK, INIT_PROTO_VERSION))},
m_serializer{std::make_unique<V1TransportSerializer>(V1TransportSerializer())},
m_permission_flags{node_opts.permission_flags},
m_sock{sock},
m_connected{GetTime<std::chrono::seconds>()},
addr{addrIn},
addrBind{addrBindIn},
m_addr_name{addrNameIn.empty() ? addr.ToStringIPPort() : addrNameIn},
m_inbound_onion{inbound_onion},
m_prefer_evict{node_opts.prefer_evict},
nKeyedNetGroup{nKeyedNetGroupIn},
id{idIn},
nLocalHostNonce{nLocalHostNonceIn},
m_conn_type{conn_type_in},
m_i2p_sam_session{std::move(i2p_sam_session)}
m_i2p_sam_session{std::move(node_opts.i2p_sam_session)}
{
if (inbound_onion) assert(conn_type_in == ConnectionType::INBOUND);

Expand Down
21 changes: 14 additions & 7 deletions src/net.h
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ class CNodeStats
mapMsgTypeSize mapSendBytesPerMsgType;
uint64_t nRecvBytes;
mapMsgTypeSize mapRecvBytesPerMsgType;
NetPermissionFlags m_permissionFlags;
NetPermissionFlags m_permission_flags;
std::chrono::microseconds m_last_ping_time;
std::chrono::microseconds m_min_ping_time;
// Our address, as reported by the peer
Expand Down Expand Up @@ -334,6 +334,13 @@ class V1TransportSerializer : public TransportSerializer {
void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) const override;
};

struct CNodeOptions
{
NetPermissionFlags permission_flags = NetPermissionFlags::None;
std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
bool prefer_evict = false;
};

/** Information about a peer */
class CNode
{
Expand All @@ -344,7 +351,7 @@ class CNode
const std::unique_ptr<TransportDeserializer> m_deserializer; // Used only by SocketHandler thread
const std::unique_ptr<const TransportSerializer> m_serializer;

NetPermissionFlags m_permissionFlags{NetPermissionFlags::None}; // treated as const outside of fuzz tester
const NetPermissionFlags m_permission_flags;

/**
* Socket used for communication with the node.
Expand Down Expand Up @@ -393,9 +400,9 @@ class CNode
* from the wire. This cleaned string can safely be logged or displayed.
*/
std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
bool m_prefer_evict{false}; // This peer is preferred for eviction. (treated as const)
const bool m_prefer_evict{false}; // This peer is preferred for eviction.
bool HasPermission(NetPermissionFlags permission) const {
return NetPermissions::HasFlag(m_permissionFlags, permission);
return NetPermissions::HasFlag(m_permission_flags, permission);
}
/** fSuccessfullyConnected is set to true on receiving VERACK from the peer. */
std::atomic_bool fSuccessfullyConnected{false};
Expand Down Expand Up @@ -522,7 +529,7 @@ class CNode
const std::string& addrNameIn,
ConnectionType conn_type_in,
bool inbound_onion,
std::unique_ptr<i2p::sam::Session>&& i2p_sam_session = nullptr);
CNodeOptions&& node_opts = {});
CNode(const CNode&) = delete;
CNode& operator=(const CNode&) = delete;

Expand Down Expand Up @@ -890,12 +897,12 @@ class CConnman
* Create a `CNode` object from a socket that has just been accepted and add the node to
* the `m_nodes` member.
* @param[in] sock Connected socket to communicate with the peer.
* @param[in] permissionFlags The peer's permissions.
* @param[in] permission_flags The peer's permissions.
* @param[in] addr_bind The address and port at our side of the connection.
* @param[in] addr The address and port at the peer's side of the connection.
*/
void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
NetPermissionFlags permissionFlags,
NetPermissionFlags permission_flags,
const CAddress& addr_bind,
const CAddress& addr);

Expand Down
4 changes: 2 additions & 2 deletions src/qt/rpcconsole.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1182,11 +1182,11 @@ void RPCConsole::updateDetailWidget()
ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer));
ui->peerConnectionType->setText(GUIUtil::ConnectionTypeToQString(stats->nodeStats.m_conn_type, /*prepend_direction=*/true));
ui->peerNetwork->setText(GUIUtil::NetworkToQString(stats->nodeStats.m_network));
if (stats->nodeStats.m_permissionFlags == NetPermissionFlags::None) {
if (stats->nodeStats.m_permission_flags == NetPermissionFlags::None) {
ui->peerPermissions->setText(ts.na);
} else {
QStringList permissions;
for (const auto& permission : NetPermissions::ToStrings(stats->nodeStats.m_permissionFlags)) {
for (const auto& permission : NetPermissions::ToStrings(stats->nodeStats.m_permission_flags)) {
permissions.append(QString::fromStdString(permission));
}
ui->peerPermissions->setText(permissions.join(" & "));
Expand Down
2 changes: 1 addition & 1 deletion src/rpc/net.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ static RPCHelpMan getpeerinfo()
obj.pushKV("addr_rate_limited", statestats.m_addr_rate_limited);
}
UniValue permissions(UniValue::VARR);
for (const auto& permission : NetPermissions::ToStrings(stats.m_permissionFlags)) {
for (const auto& permission : NetPermissions::ToStrings(stats.m_permission_flags)) {
permissions.push_back(permission);
}
obj.pushKV("permissions", permissions);
Expand Down
1 change: 0 additions & 1 deletion src/test/denialofservice_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ BOOST_AUTO_TEST_CASE(outbound_slow_chain_eviction)
/*successfully_connected=*/true,
/*remote_services=*/ServiceFlags(NODE_NETWORK | NODE_WITNESS),
/*local_services=*/ServiceFlags(NODE_NETWORK | NODE_WITNESS),
/*permission_flags=*/NetPermissionFlags::None,
/*version=*/PROTOCOL_VERSION,
/*relay_txs=*/true);
TestOnlyResetTimeData();
Expand Down
1 change: 0 additions & 1 deletion src/test/fuzz/util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,6 @@ void FillNode(FuzzedDataProvider& fuzzed_data_provider, ConnmanTestMsg& connman,
/*successfully_connected=*/fuzzed_data_provider.ConsumeBool(),
/*remote_services=*/ConsumeWeakEnum(fuzzed_data_provider, ALL_SERVICE_FLAGS),
/*local_services=*/ConsumeWeakEnum(fuzzed_data_provider, ALL_SERVICE_FLAGS),
/*permission_flags=*/ConsumeWeakEnum(fuzzed_data_provider, ALL_NET_PERMISSION_FLAGS),
/*version=*/fuzzed_data_provider.ConsumeIntegralInRange<int32_t>(MIN_PEER_PROTO_VERSION, std::numeric_limits<int32_t>::max()),
/*relay_txs=*/fuzzed_data_provider.ConsumeBool());
}
Expand Down
7 changes: 5 additions & 2 deletions src/test/fuzz/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,7 @@ auto ConsumeNode(FuzzedDataProvider& fuzzed_data_provider, const std::optional<N
const std::string addr_name = fuzzed_data_provider.ConsumeRandomLengthString(64);
const ConnectionType conn_type = fuzzed_data_provider.PickValueInArray(ALL_CONNECTION_TYPES);
const bool inbound_onion{conn_type == ConnectionType::INBOUND ? fuzzed_data_provider.ConsumeBool() : false};
NetPermissionFlags permission_flags = ConsumeWeakEnum(fuzzed_data_provider, ALL_NET_PERMISSION_FLAGS);
if constexpr (ReturnUniquePtr) {
return std::make_unique<CNode>(node_id,
sock,
Expand All @@ -310,7 +311,8 @@ auto ConsumeNode(FuzzedDataProvider& fuzzed_data_provider, const std::optional<N
addr_bind,
addr_name,
conn_type,
inbound_onion);
inbound_onion,
CNodeOptions{ .permission_flags = permission_flags });
} else {
return CNode{node_id,
sock,
Expand All @@ -320,7 +322,8 @@ auto ConsumeNode(FuzzedDataProvider& fuzzed_data_provider, const std::optional<N
addr_bind,
addr_name,
conn_type,
inbound_onion};
inbound_onion,
CNodeOptions{ .permission_flags = permission_flags }};
}
}
inline std::unique_ptr<CNode> ConsumeNodeAsUniquePtr(FuzzedDataProvider& fdp, const std::optional<NodeId>& node_id_in = std::nullopt) { return ConsumeNode<true>(fdp, node_id_in); }
Expand Down
2 changes: 0 additions & 2 deletions src/test/util/net.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ void ConnmanTestMsg::Handshake(CNode& node,
bool successfully_connected,
ServiceFlags remote_services,
ServiceFlags local_services,
NetPermissionFlags permission_flags,
int32_t version,
bool relay_txs)
{
Expand Down Expand Up @@ -56,7 +55,6 @@ void ConnmanTestMsg::Handshake(CNode& node,
assert(peerman.GetNodeStateStats(node.GetId(), statestats));
assert(statestats.m_relay_txs == (relay_txs && !node.IsBlockOnlyConn()));
assert(statestats.their_services == remote_services);
node.m_permissionFlags = permission_flags;
if (successfully_connected) {
CSerializedNetMsg msg_verack{mm.Make(NetMsgType::VERACK)};
(void)connman.ReceiveMsgFrom(node, msg_verack);
Expand Down
1 change: 0 additions & 1 deletion src/test/util/net.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ struct ConnmanTestMsg : public CConnman {
bool successfully_connected,
ServiceFlags remote_services,
ServiceFlags local_services,
NetPermissionFlags permission_flags,
int32_t version,
bool relay_txs);

Expand Down

0 comments on commit ea67232

Please sign in to comment.