From 94e8882d820969ddc83f24f4cbe1515a886da4ea Mon Sep 17 00:00:00 2001 From: Sergi Delgado Segura Date: Tue, 25 Jul 2023 15:29:00 -0400 Subject: [PATCH] rpc: Prevents adding the same ip more than once when formatted differently Currently it is possible to add the same node twice when formatting IPs in different, yet equivalent, manner. This applies to both ipv4 and ipv6, e.g: 127.0.0.1 = 127.1 | [::1] = [0:0:0:0:0:0:0:1] `addnode` will accept both and display both as connected (given they translate to the same IP). This will not result in multiple connections to the same node, but will report redundant info when querying `getaddednodeinfo` and populate `m_added_nodes` with redundant data. This can be avoided performing comparing the contents of `m_added_addr` and the address to be added as `CServices` instead of as strings. --- src/net.cpp | 5 ++++- test/functional/rpc_net.py | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/net.cpp b/src/net.cpp index 0d4b3859c0f..54a1eb64770 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -3471,9 +3471,12 @@ std::vector CConnman::GetAddresses(CNode& requestor, size_t max_addres bool CConnman::AddNode(const AddedNodeParams& add) { + const CService resolved(LookupNumeric(add.m_added_node, GetDefaultPort(add.m_added_node))); + const bool resolved_is_valid{resolved.IsValid()}; + LOCK(m_added_nodes_mutex); for (const auto& it : m_added_node_params) { - if (add.m_added_node == it.m_added_node) return false; + if (add.m_added_node == it.m_added_node || (resolved_is_valid && resolved == LookupNumeric(it.m_added_node, GetDefaultPort(it.m_added_node)))) return false; } m_added_node_params.push_back(add); diff --git a/test/functional/rpc_net.py b/test/functional/rpc_net.py index 2c7f974d0bb..19fbca7fa93 100755 --- a/test/functional/rpc_net.py +++ b/test/functional/rpc_net.py @@ -215,8 +215,11 @@ class NetTest(BitcoinTestFramework): # add a node (node2) to node0 ip_port = "127.0.0.1:{}".format(p2p_port(2)) self.nodes[0].addnode(node=ip_port, command='add') + # try to add an equivalent ip + ip_port2 = "127.1:{}".format(p2p_port(2)) + assert_raises_rpc_error(-23, "Node already added", self.nodes[0].addnode, node=ip_port2, command='add') # check that the node has indeed been added - added_nodes = self.nodes[0].getaddednodeinfo(ip_port) + added_nodes = self.nodes[0].getaddednodeinfo() assert_equal(len(added_nodes), 1) assert_equal(added_nodes[0]['addednode'], ip_port) # check that node cannot be added again