Debian Codegraph @

monero/tests/unit_tests/node_server.cpp

raw symbols SCIP
1 // Copyright (c) 2014-2022, The Monero Project
2 //
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without modification, are
6 // permitted provided that the following conditions are met:
7 //
8 // 1. Redistributions of source code must retain the above copyright notice, this list of
9 // conditions and the following disclaimer.
10 //
11 // 2. Redistributions in binary form must reproduce the above copyright notice, this list
12 // of conditions and the following disclaimer in the documentation and/or other
13 // materials provided with the distribution.
14 //
15 // 3. Neither the name of the copyright holder nor the names of its contributors may be
16 // used to endorse or promote products derived from this software without specific
17 // prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
20 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27 // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 //
29 // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
30
31 #include "gtest/gtest.h"
32 #include "cryptonote_core/cryptonote_core.h"
33 #include "p2p/net_node.h"
34 #include "p2p/net_node.inl"
35 #include "cryptonote_core/i_core_events.h"
36 #include "cryptonote_protocol/cryptonote_protocol_handler.h"
37 #include "cryptonote_protocol/cryptonote_protocol_handler.inl"
38 #include "unit_tests_utils.h"
39 #include <condition_variable>
40
41 #define MAKE_IPV4_ADDRESS(a,b,c,d) epee::net_utils::ipv4_network_address{MAKE_IP(a,b,c,d),0}
42 #define MAKE_IPV4_ADDRESS_PORT(a,b,c,d,e) epee::net_utils::ipv4_network_address{MAKE_IP(a,b,c,d),e}
43 #define MAKE_IPV4_SUBNET(a,b,c,d,e) epee::net_utils::ipv4_network_subnet{MAKE_IP(a,b,c,d),e}
44
45 namespace cryptonote {
46 class blockchain_storage;
47 }
48
49 class test_core : public cryptonote::i_core_events
50 {
51 public:
52 virtual bool is_synchronized() const final { return true; }
53 void on_synchronized(){}
54 void safesyncmode(const bool){}
55 virtual uint64_t get_current_blockchain_height() const final {return 1;}
56 void set_target_blockchain_height(uint64_t) {}
57 bool init(const boost::program_options::variables_map& vm) {return true ;}
58 bool deinit(){return true;}
59 bool get_short_chain_history(std::list<crypto::hash>& ids) const { return true; }
60 bool have_block(const crypto::hash& id, int *where = NULL) const {return false;}
61 bool have_block_unlocked(const crypto::hash& id, int *where = NULL) const {return false;}
62 void get_blockchain_top(uint64_t& height, crypto::hash& top_id)const{height=0;top_id=crypto::null_hash;}
63 bool handle_incoming_tx(const cryptonote::blobdata& tx_blob, cryptonote::tx_verification_context& tvc, cryptonote::relay_method tx_relay, bool relayed) { return true; }
64 bool handle_single_incoming_block(const cryptonote::blobdata& block_blob, const cryptonote::block *b, cryptonote::block_verification_context& bvc, cryptonote::pool_supplement& extra_block_txs, bool update_miner_blocktemplate = true) { return true; }
65 bool handle_incoming_block(const cryptonote::blobdata& block_blob, const cryptonote::block *block, cryptonote::block_verification_context& bvc, bool update_miner_blocktemplate = true) { return true; }
66 bool handle_incoming_block(const cryptonote::blobdata& block_blob, const cryptonote::block *block, cryptonote::block_verification_context& bvc, cryptonote::pool_supplement& extra_block_txs, bool update_miner_blocktemplate = true) { return true; }
67 void pause_mine(){}
68 void resume_mine(){}
69 bool on_idle(){return true;}
70 bool find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, bool clip_pruned, cryptonote::NOTIFY_RESPONSE_CHAIN_ENTRY::request& resp){return true;}
71 bool handle_get_objects(cryptonote::NOTIFY_REQUEST_GET_OBJECTS::request& arg, cryptonote::NOTIFY_RESPONSE_GET_OBJECTS::request& rsp, cryptonote::cryptonote_connection_context& context){return true;}
72 cryptonote::blockchain_storage &get_blockchain_storage() { throw std::runtime_error("Called invalid member function: please never call get_blockchain_storage on the TESTING class test_core."); }
73 bool get_test_drop_download() const {return true;}
74 bool get_test_drop_download_height() const {return true;}
75 bool prepare_handle_incoming_blocks(const std::vector<cryptonote::block_complete_entry> &blocks_entry, std::vector<cryptonote::block> &blocks) { return true; }
76 bool cleanup_handle_incoming_blocks(bool force_sync = false) { return true; }
77 bool check_incoming_block_size(const cryptonote::blobdata& block_blob) const { return true; }
78 bool update_checkpoints(const bool skip_dns = false) { return true; }
79 uint64_t get_target_blockchain_height() const { return 1; }
80 size_t get_block_sync_size(uint64_t height) const { return BLOCKS_SYNCHRONIZING_DEFAULT_COUNT; }
81 virtual void on_transactions_relayed(epee::span<const cryptonote::blobdata> tx_blobs, cryptonote::relay_method tx_relay) {}
82 cryptonote::network_type get_nettype() const { return cryptonote::MAINNET; }
83 bool get_pool_transaction(const crypto::hash& id, cryptonote::blobdata& tx_blob, cryptonote::relay_category tx_category) const { return false; }
84 bool pool_has_tx(const crypto::hash &txid) const { return false; }
85 bool get_blocks(uint64_t start_offset, size_t count, std::vector<std::pair<cryptonote::blobdata, cryptonote::block>>& blocks, std::vector<cryptonote::blobdata>& txs) const { return false; }
86 bool get_transactions(const std::vector<crypto::hash>& txs_ids, std::vector<cryptonote::blobdata>& txs, std::vector<crypto::hash>& missed_txs, bool pruned = false) const { return false; }
87 bool get_transactions(const std::vector<crypto::hash>& txs_ids, std::vector<cryptonote::transaction>& txs, std::vector<crypto::hash>& missed_txs) const { return false; }
88 bool get_block_by_hash(const crypto::hash &h, cryptonote::block &blk, bool *orphan = NULL) const { return false; }
89 uint8_t get_ideal_hard_fork_version() const { return 0; }
90 uint8_t get_ideal_hard_fork_version(uint64_t height) const { return 0; }
91 uint8_t get_hard_fork_version(uint64_t height) const { return 0; }
92 uint64_t get_earliest_ideal_height_for_version(uint8_t version) const { return 0; }
93 cryptonote::difficulty_type get_block_cumulative_difficulty(uint64_t height) const { return 0; }
94 uint64_t prevalidate_block_hashes(uint64_t height, const std::vector<crypto::hash> &hashes, const std::vector<uint64_t> &weights) { return 0; }
95 bool pad_transactions() { return false; }
96 uint32_t get_blockchain_pruning_seed() const { return 0; }
97 bool prune_blockchain(uint32_t pruning_seed = 0) { return true; }
98 bool is_within_compiled_block_hash_area(uint64_t height) const { return false; }
99 bool has_block_weights(uint64_t height, uint64_t nblocks) const { return false; }
100 bool get_txpool_complement(const std::vector<crypto::hash> &hashes, std::vector<cryptonote::blobdata> &txes) { return false; }
101 bool get_pool_transaction_hashes(std::vector<crypto::hash>& txs, bool include_unrelayed_txes = true) const { return false; }
102 crypto::hash get_block_id_by_height(uint64_t height) const { return crypto::null_hash; }
103 void stop() {}
104 };
105
106 typedef nodetool::node_server<cryptonote::t_cryptonote_protocol_handler<test_core>> Server;
107
108 static bool is_blocked(Server &server, const epee::net_utils::network_address &address, time_t *t = NULL)
109 {
110 std::map<std::string, time_t> hosts = server.get_blocked_hosts();
111 for (auto rec: hosts)
112 {
113 if (rec.first == address.host_str())
114 {
115 if (t)
116 *t = rec.second;
117 return true;
118 }
119 }
120
121 if (address.get_type_id() != epee::net_utils::address_type::ipv4)
122 return false;
123
124 const epee::net_utils::ipv4_network_address ipv4_address = address.as<epee::net_utils::ipv4_network_address>();
125
126 // check if in a blocked ipv4 subnet
127 const std::map<epee::net_utils::ipv4_network_subnet, time_t> subnets = server.get_blocked_subnets();
128 for (const auto &subnet : subnets)
129 if (subnet.first.matches(ipv4_address))
130 return true;
131
132 return false;
133 }
134
135 TEST(ban, add)
136 {
137 test_core pr_core;
138 cryptonote::t_cryptonote_protocol_handler<test_core> cprotocol(pr_core, NULL);
139 Server server(cprotocol);
140 cprotocol.set_p2p_endpoint(&server);
141
142 // starts empty
143 ASSERT_TRUE(server.get_blocked_hosts().empty());
144 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,4)));
145 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,5)));
146
147 // add an IP
148 ASSERT_TRUE(server.block_host(MAKE_IPV4_ADDRESS(1,2,3,4)));
149 ASSERT_TRUE(server.get_blocked_hosts().size() == 1);
150 ASSERT_TRUE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,4)));
151 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,5)));
152
153 // add the same, should not change
154 ASSERT_TRUE(server.block_host(MAKE_IPV4_ADDRESS(1,2,3,4)));
155 ASSERT_TRUE(server.get_blocked_hosts().size() == 1);
156 ASSERT_TRUE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,4)));
157 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,5)));
158
159 // remove an unblocked IP, should not change
160 ASSERT_FALSE(server.unblock_host(MAKE_IPV4_ADDRESS(1,2,3,5)));
161 ASSERT_TRUE(server.get_blocked_hosts().size() == 1);
162 ASSERT_TRUE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,4)));
163 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,5)));
164
165 // remove the IP, ends up empty
166 ASSERT_TRUE(server.unblock_host(MAKE_IPV4_ADDRESS(1,2,3,4)));
167 ASSERT_TRUE(server.get_blocked_hosts().size() == 0);
168 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,4)));
169 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,5)));
170
171 // remove the IP from an empty list, still empty
172 ASSERT_FALSE(server.unblock_host(MAKE_IPV4_ADDRESS(1,2,3,4)));
173 ASSERT_TRUE(server.get_blocked_hosts().size() == 0);
174 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,4)));
175 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,5)));
176
177 // add two for known amounts of time, they're both blocked
178 ASSERT_TRUE(server.block_host(MAKE_IPV4_ADDRESS(1,2,3,4), 1));
179 ASSERT_TRUE(server.block_host(MAKE_IPV4_ADDRESS(1,2,3,5), 3));
180 ASSERT_TRUE(server.get_blocked_hosts().size() == 2);
181 ASSERT_TRUE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,4)));
182 ASSERT_TRUE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,5)));
183 ASSERT_TRUE(server.unblock_host(MAKE_IPV4_ADDRESS(1,2,3,4)));
184 ASSERT_TRUE(server.unblock_host(MAKE_IPV4_ADDRESS(1,2,3,5)));
185
186 // these tests would need to call is_remote_ip_allowed, which is private
187 #if 0
188 // after two seconds, the first IP is unblocked, but not the second yet
189 sleep(2);
190 ASSERT_TRUE(server.get_blocked_hosts().size() == 1);
191 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,4)));
192 ASSERT_TRUE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,5)));
193
194 // after two more seconds, the second IP is also unblocked
195 sleep(2);
196 ASSERT_TRUE(server.get_blocked_hosts().size() == 0);
197 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,4)));
198 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,5)));
199 #endif
200
201 // add an IP again, then re-ban for longer, then shorter
202 time_t t;
203 ASSERT_TRUE(server.block_host(MAKE_IPV4_ADDRESS(1,2,3,4), 2));
204 ASSERT_TRUE(server.get_blocked_hosts().size() == 1);
205 ASSERT_TRUE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,4), &t));
206 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,5)));
207 ASSERT_TRUE(t >= 1);
208 ASSERT_TRUE(server.block_host(MAKE_IPV4_ADDRESS(1,2,3,4), 9));
209 ASSERT_TRUE(server.get_blocked_hosts().size() == 1);
210 ASSERT_TRUE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,4), &t));
211 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,5)));
212 ASSERT_TRUE(t >= 8);
213 ASSERT_TRUE(server.block_host(MAKE_IPV4_ADDRESS(1,2,3,4), 5));
214 ASSERT_TRUE(server.get_blocked_hosts().size() == 1);
215 ASSERT_TRUE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,4), &t));
216 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,5)));
217 ASSERT_TRUE(t >= 4);
218 }
219
220 TEST(ban, limit)
221 {
222 test_core pr_core;
223 cryptonote::t_cryptonote_protocol_handler<test_core> cprotocol(pr_core, NULL);
224 Server server(cprotocol);
225 cprotocol.set_p2p_endpoint(&server);
226
227 // starts empty
228 ASSERT_TRUE(server.get_blocked_hosts().empty());
229 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,4)));
230 ASSERT_TRUE(server.block_host(MAKE_IPV4_ADDRESS(1,2,3,4), std::numeric_limits<time_t>::max() - 1));
231 ASSERT_TRUE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,4)));
232 ASSERT_TRUE(server.block_host(MAKE_IPV4_ADDRESS(1,2,3,4), 1));
233 ASSERT_TRUE(is_blocked(server,MAKE_IPV4_ADDRESS(1,2,3,4)));
234 }
235
236 TEST(ban, subnet)
237 {
238 time_t seconds;
239 test_core pr_core;
240 cryptonote::t_cryptonote_protocol_handler<test_core> cprotocol(pr_core, NULL);
241 Server server(cprotocol);
242 {
243 boost::program_options::options_description opts{};
244 Server::init_options(opts);
245 cryptonote::core::init_options(opts);
246
247 char** args = nullptr;
248 boost::program_options::variables_map vm;
249 boost::program_options::store(
250 boost::program_options::parse_command_line(0, args, opts), vm
251 );
252 server.init(vm);
253 }
254 cprotocol.set_p2p_endpoint(&server);
255
256 ASSERT_TRUE(server.block_subnet(MAKE_IPV4_SUBNET(1,2,3,4,24), 10));
257 ASSERT_TRUE(server.get_blocked_subnets().size() == 1);
258 ASSERT_TRUE(server.is_host_blocked(MAKE_IPV4_ADDRESS(1,2,3,4), &seconds));
259 ASSERT_TRUE(seconds >= 9);
260 ASSERT_TRUE(server.is_host_blocked(MAKE_IPV4_ADDRESS(1,2,3,255), &seconds));
261 ASSERT_TRUE(server.is_host_blocked(MAKE_IPV4_ADDRESS(1,2,3,0), &seconds));
262 ASSERT_FALSE(server.is_host_blocked(MAKE_IPV4_ADDRESS(1,2,4,0), &seconds));
263 ASSERT_FALSE(server.is_host_blocked(MAKE_IPV4_ADDRESS(1,2,2,0), &seconds));
264 ASSERT_TRUE(server.unblock_subnet(MAKE_IPV4_SUBNET(1,2,3,8,24)));
265 ASSERT_TRUE(server.get_blocked_subnets().size() == 0);
266 ASSERT_FALSE(server.is_host_blocked(MAKE_IPV4_ADDRESS(1,2,3,255), &seconds));
267 ASSERT_FALSE(server.is_host_blocked(MAKE_IPV4_ADDRESS(1,2,3,0), &seconds));
268 ASSERT_TRUE(server.block_subnet(MAKE_IPV4_SUBNET(1,2,3,4,8), 10));
269 ASSERT_TRUE(server.get_blocked_subnets().size() == 1);
270 ASSERT_TRUE(server.is_host_blocked(MAKE_IPV4_ADDRESS(1,255,3,255), &seconds));
271 ASSERT_TRUE(server.is_host_blocked(MAKE_IPV4_ADDRESS(1,0,3,255), &seconds));
272 ASSERT_FALSE(server.unblock_subnet(MAKE_IPV4_SUBNET(1,2,3,8,24)));
273 ASSERT_TRUE(server.get_blocked_subnets().size() == 1);
274 ASSERT_TRUE(server.block_subnet(MAKE_IPV4_SUBNET(1,2,3,4,8), 10));
275 ASSERT_TRUE(server.get_blocked_subnets().size() == 1);
276 ASSERT_TRUE(server.unblock_subnet(MAKE_IPV4_SUBNET(1,255,0,0,8)));
277 ASSERT_TRUE(server.get_blocked_subnets().size() == 0);
278 }
279
280 TEST(ban, ignores_port)
281 {
282 test_core pr_core;
283 cryptonote::t_cryptonote_protocol_handler<test_core> cprotocol(pr_core, NULL);
284 Server server(cprotocol);
285 cprotocol.set_p2p_endpoint(&server);
286
287 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS_PORT(1,2,3,4,5)));
288 ASSERT_TRUE(server.block_host(MAKE_IPV4_ADDRESS_PORT(1,2,3,4,5), std::numeric_limits<time_t>::max() - 1));
289 ASSERT_TRUE(is_blocked(server,MAKE_IPV4_ADDRESS_PORT(1,2,3,4,5)));
290 ASSERT_TRUE(is_blocked(server,MAKE_IPV4_ADDRESS_PORT(1,2,3,4,6)));
291 ASSERT_TRUE(server.unblock_host(MAKE_IPV4_ADDRESS_PORT(1,2,3,4,5)));
292 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS_PORT(1,2,3,4,5)));
293 ASSERT_FALSE(is_blocked(server,MAKE_IPV4_ADDRESS_PORT(1,2,3,4,6)));
294 }
295
296 TEST(ban, file_banlist)
297 {
298 test_core pr_core;
299 cryptonote::t_cryptonote_protocol_handler<test_core> cprotocol(pr_core, NULL);
300 Server server(cprotocol);
301 cprotocol.set_p2p_endpoint(&server);
302
303 auto create_node_dir = [](){
304 boost::system::error_code ec;
305 auto path = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("daemon-%%%%%%%%%%%%%%%%", ec);
306 if (ec)
307 return boost::filesystem::path{};
308 auto success = boost::filesystem::create_directory(path, ec);
309 if (!ec && success)
310 return path;
311 return boost::filesystem::path{};
312 };
313 const auto node_dir = create_node_dir();
314 ASSERT_TRUE(!node_dir.empty());
315 auto auto_remove_node_dir = epee::misc_utils::create_scope_leave_handler([&node_dir](){
316 boost::filesystem::remove_all(node_dir);
317 });
318
319 boost::program_options::variables_map vm;
320 boost::program_options::store(
321 boost::program_options::command_line_parser({
322 "--data-dir",
323 node_dir.string(),
324 "--ban-list",
325 (unit_test::data_dir / "node" / "banlist_1.txt").string()
326 }).options([]{
327 boost::program_options::options_description options_description{};
328 cryptonote::core::init_options(options_description);
329 Server::init_options(options_description);
330 return options_description;
331 }()).run(),
332 vm
333 );
334
335 ASSERT_TRUE(server.init(vm));
336
337 // Test cases (look in the banlist_1.txt file)
338
339 // magicfolk
340 EXPECT_TRUE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(255,255,255,0,9999)) );
341 EXPECT_TRUE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(128,128,128,0,9999)) );
342 EXPECT_TRUE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(150,75,0,0,9999)) );
343 EXPECT_TRUE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(99,98,0,0,9999)) );
344 EXPECT_TRUE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(99,98,0,255,9999)) );
345 EXPECT_TRUE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(99,98,1,0,9999)) );
346 EXPECT_TRUE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(99,98,1,0,9999)) );
347 EXPECT_TRUE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(99,98,255,255,9999)) );
348 EXPECT_FALSE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(99,99,0,0,9999)) );
349
350 // personal enemies
351 EXPECT_TRUE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(1,2,3,4,9999)) );
352 EXPECT_TRUE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(6,7,8,9,9999)) );
353 EXPECT_TRUE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(1,0,0,7,9999)) );
354 EXPECT_TRUE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(1,0,0,7,9999)) );
355 EXPECT_TRUE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(100,98,1,13,9999)) );
356 EXPECT_TRUE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(100,98,1,0,9999)) );
357 EXPECT_TRUE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(100,98,1,255,9999)) );
358 EXPECT_FALSE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(100,98,2,0,9999)) );
359 EXPECT_FALSE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(100,98,0,255,9999)) );
360
361 // angel
362 EXPECT_FALSE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(007,007,007,007,9999)) );
363
364 // random IP
365 EXPECT_FALSE( is_blocked(server, MAKE_IPV4_ADDRESS_PORT(145,036,205,235,9999)) );
366 }
367
368 TEST(node_server, bind_same_p2p_port)
369 {
370 struct test_data_t
371 {
372 test_core pr_core;
373 cryptonote::t_cryptonote_protocol_handler<test_core> cprotocol;
374 std::unique_ptr<Server> server;
375
376 test_data_t(): cprotocol(pr_core, NULL)
377 {
378 server.reset(new Server(cprotocol));
379 cprotocol.set_p2p_endpoint(server.get());
380 }
381 };
382
383 const auto new_node = []() -> std::unique_ptr<test_data_t> {
384 test_data_t *d = new test_data_t;
385 return std::unique_ptr<test_data_t>(d);
386 };
387
388 const auto init = [](const std::unique_ptr<test_data_t>& server, const char* port) -> bool {
389 boost::program_options::options_description desc_options("Command line options");
390 cryptonote::core::init_options(desc_options);
391 Server::init_options(desc_options);
392
393 const char *argv[2] = {nullptr, nullptr};
394 boost::program_options::variables_map vm;
395 boost::program_options::store(boost::program_options::parse_command_line(1, argv, desc_options), vm);
396
397 /*
398 Reason for choosing '127.0.0.2' as the IP:
399
400 A TCP local socket address that has been bound is unavailable for some time after closing, unless the SO_REUSEADDR flag has been set.
401 That's why connections with automatically assigned source port 48080/58080 from previous test blocks the next to bind acceptor
402 so solution is to either set reuse_addr option for each socket in all tests
403 or use ip different from localhost for acceptors in order to not interfere with automatically assigned source endpoints
404
405 Relevant part about REUSEADDR from man:
406 https://www.man7.org/linux/man-pages/man7/ip.7.html
407
408 For Mac OSX, set the following alias, before running the test, or else it will fail:
409 sudo ifconfig lo0 alias 127.0.0.2
410 */
411 vm.find(nodetool::arg_p2p_bind_ip.name)->second = boost::program_options::variable_value(std::string("127.0.0.2"), false);
412 vm.find(nodetool::arg_p2p_bind_port.name)->second = boost::program_options::variable_value(std::string(port), false);
413
414 boost::program_options::notify(vm);
415
416 return server->server->init(vm);
417 };
418
419 constexpr char port[] = "48080";
420 constexpr char port_another[] = "58080";
421
422 const auto node = new_node();
423 EXPECT_TRUE(init(node, port));
424
425 EXPECT_FALSE(init(new_node(), port));
426 EXPECT_TRUE(init(new_node(), port_another));
427 }
428
429 TEST(cryptonote_protocol_handler, race_condition)
430 {
431 struct contexts {
432 using basic = epee::net_utils::connection_context_base;
433 using cryptonote = cryptonote::cryptonote_connection_context;
434 using p2p = nodetool::p2p_connection_context_t<cryptonote>;
435 };
436 using context_t = contexts::p2p;
437 using handler_t = epee::levin::async_protocol_handler<context_t>;
438 using connection_t = epee::net_utils::connection<handler_t>;
439 using connection_ptr = boost::shared_ptr<connection_t>;
440 using connections_t = std::vector<connection_ptr>;
441 using shared_state_t = typename connection_t::shared_state;
442 using shared_state_ptr = std::shared_ptr<shared_state_t>;
443 using io_context_t = boost::asio::io_context;
444 using event_t = epee::simple_event;
445 using ec_t = boost::system::error_code;
446 auto create_conn_pair = [](connection_ptr in, connection_ptr out) {
447 using endpoint_t = boost::asio::ip::tcp::endpoint;
448 using acceptor_t = boost::asio::ip::tcp::acceptor;
449 io_context_t io_context;
450 endpoint_t endpoint(boost::asio::ip::make_address("127.0.0.1"), 5262);
451 acceptor_t acceptor(io_context);
452 ec_t ec;
453 acceptor.open(endpoint.protocol(), ec);
454 EXPECT_EQ(ec.value(), 0);
455 acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
456 acceptor.bind(endpoint, ec);
457 EXPECT_EQ(ec.value(), 0);
458 acceptor.listen(boost::asio::socket_base::max_listen_connections, ec);
459 EXPECT_EQ(ec.value(), 0);
460 out->socket().open(endpoint.protocol(), ec);
461 EXPECT_EQ(ec.value(), 0);
462 acceptor.async_accept(in->socket(), [](const ec_t &ec){});
463 out->socket().async_connect(endpoint, [](const ec_t &ec){});
464 io_context.run();
465 acceptor.close(ec);
466 EXPECT_EQ(ec.value(), 0);
467 EXPECT_TRUE(in->start(true, true));
468 EXPECT_TRUE(out->start(false, true));
469 return std::make_pair<>(std::move(in), std::move(out));
470 };
471 auto get_conn_tag = [](connection_t &conn){
472 context_t context;
473 conn.get_context(context);
474 return context.m_connection_id;
475 };
476 using work_t = boost::asio::executor_work_guard<boost::asio::io_context::executor_type>;
477 using work_ptr = std::shared_ptr<work_t>;
478 using workers_t = std::vector<std::thread>;
479 using commands_handler_t = epee::levin::levin_commands_handler<context_t>;
480 using p2p_endpoint_t = nodetool::i_p2p_endpoint<contexts::cryptonote>;
481 using core_t = cryptonote::core;
482 using core_ptr = std::unique_ptr<core_t>;
483 using core_protocol_t = cryptonote::t_cryptonote_protocol_handler<core_t>;
484 using core_protocol_ptr = std::shared_ptr<core_protocol_t>;
485 using block_t = cryptonote::block;
486 using diff_t = cryptonote::difficulty_type;
487 using reward_t = uint64_t;
488 using height_t = uint64_t;
489 struct span {
490 using blocks = epee::span<const block_t>;
491 };
492 auto get_block_template = [](
493 core_t &core,
494 block_t &block,
495 diff_t &diff,
496 reward_t &reward
497 ){
498 auto &storage = core.get_blockchain_storage();
499 const auto height = storage.get_current_blockchain_height();
500 const auto hardfork = storage.get_current_hard_fork_version();
501 block.major_version = hardfork;
502 block.minor_version = storage.get_ideal_hard_fork_version();
503 block.prev_id = storage.get_tail_id();
504 auto &db = storage.get_db();
505 block.timestamp = db.get_top_block_timestamp();
506 block.nonce = 0xACAB;
507 block.miner_tx.vin.clear();
508 block.miner_tx.vout.clear();
509 block.miner_tx.extra.clear();
510 block.miner_tx.version = hardfork >= 4 ? 2 : 1;
511 block.miner_tx.unlock_time = height + CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW;
512 block.miner_tx.vin.push_back(cryptonote::txin_gen{height});
513 cryptonote::add_tx_pub_key_to_extra(block.miner_tx, {});
514 cryptonote::get_block_reward(
515 db.get_block_weight(height - 1),
516 {},
517 db.get_block_already_generated_coins(height - 1),
518 reward,
519 hardfork
520 );
521 block.miner_tx.vout.push_back(cryptonote::tx_out{reward, cryptonote::txout_to_key{}});
522 diff = storage.get_difficulty_for_next_block();
523 };
524 struct stat {
525 struct chain {
526 diff_t diff;
527 reward_t reward;
528 };
529 };
530 auto add_block = [](
531 core_t &core,
532 const block_t &block,
533 const stat::chain &stat
534 ){
535 core.get_blockchain_storage().get_db().batch_start({}, {});
536 core.get_blockchain_storage().get_db().add_block(
537 {block, cryptonote::block_to_blob(block)},
538 cryptonote::get_transaction_weight(block.miner_tx),
539 core.get_blockchain_storage().get_next_long_term_block_weight(
540 cryptonote::get_transaction_weight(block.miner_tx)
541 ),
542 stat.diff,
543 stat.reward,
544 {}
545 );
546 core.get_blockchain_storage().get_db().batch_stop();
547 };
548 struct messages {
549 struct core {
550 using sync = cryptonote::CORE_SYNC_DATA;
551 };
552 using handshake = nodetool::COMMAND_HANDSHAKE_T<core::sync>;
553 };
554 struct net_node_t: commands_handler_t, p2p_endpoint_t {
555 using span_t = epee::span<const uint8_t>;
556 using zone_t = epee::net_utils::zone;
557 using uuid_t = boost::uuids::uuid;
558 using relay_t = cryptonote::relay_method;
559 using blobs_t = std::vector<cryptonote::blobdata>;
560 using id_t = nodetool::peerid_type;
561 using callback_t = std::function<bool(contexts::cryptonote &, id_t, uint32_t)>;
562 using address_t = epee::net_utils::network_address;
563 using connections_t = std::vector<std::pair<zone_t, uuid_t>>;
564 struct bans {
565 using subnets = std::map<epee::net_utils::ipv4_network_subnet, time_t>;
566 using hosts = std::map<std::string, time_t>;
567 };
568 shared_state_ptr shared_state;
569 core_protocol_ptr core_protocol;
570 virtual int invoke(int command, const span_t in, epee::byte_stream &out, context_t &context) override {
571 if (core_protocol) {
572 if (command == messages::handshake::ID) {
573 return epee::net_utils::buff_to_t_adapter<void, typename messages::handshake::request, typename messages::handshake::response>(
574 command,
575 in,
576 out,
577 [this](int command, typename messages::handshake::request &in, typename messages::handshake::response &out, context_t &context){
578 core_protocol->process_payload_sync_data(in.payload_data, context, true);
579 core_protocol->get_payload_sync_data(out.payload_data);
580 return 1;
581 },
582 context
583 );
584 }
585 bool handled;
586 return core_protocol->handle_invoke_map(false, command, in, out, context, handled);
587 }
588 else
589 return {};
590 }
591 virtual int notify(int command, const span_t in, context_t &context) override {
592 if (core_protocol) {
593 bool handled;
594 epee::byte_stream out;
595 return core_protocol->handle_invoke_map(true, command, in, out, context, handled);
596 }
597 else
598 return {};
599 }
600 virtual void callback(context_t &context) override {
601 if (core_protocol)
602 core_protocol->on_callback(context);
603 }
604 virtual void on_connection_new(context_t&) override {}
605 virtual void on_connection_close(context_t &context) override {
606 if (core_protocol)
607 core_protocol->on_connection_close(context);
608 }
609 virtual ~net_node_t() override {}
610 virtual bool add_host_fail(const address_t&, unsigned int = {}) override {
611 return {};
612 }
613 virtual bool block_host(address_t address, time_t = {}, bool = {}) override {
614 return {};
615 }
616 virtual bool drop_connection(const contexts::basic& context) override {
617 if (shared_state)
618 return shared_state->close(context.m_connection_id);
619 else
620 return {};
621 }
622 virtual bool for_connection(const uuid_t& uuid, callback_t f) override {
623 if (shared_state)
624 return shared_state->for_connection(uuid,[&f](context_t &context){
625 return f(context, context.peer_id, context.support_flags);
626 });
627 else
628 return {};
629 }
630 virtual bool invoke_notify_to_peer(int command, epee::levin::message_writer in, const contexts::basic& context) override {
631 if (shared_state)
632 return shared_state->send(in.finalize_notify(command), context.m_connection_id);
633 else
634 return {};
635 }
636 virtual bool relay_notify_to_list(int command, epee::levin::message_writer in, connections_t connections) override {
637 if (shared_state) {
638 for (auto &e: connections)
639 shared_state->send(in.finalize_notify(command), e.second);
640 }
641 return {};
642 }
643 virtual bool unblock_host(const address_t&) override {
644 return {};
645 }
646 virtual zone_t send_txs(blobs_t, const zone_t, const uuid_t&, relay_t) override {
647 return {};
648 }
649 virtual bans::subnets get_blocked_subnets() override {
650 return {};
651 }
652 virtual bans::hosts get_blocked_hosts() override {
653 return {};
654 }
655 virtual uint64_t get_public_connections_count() override {
656 if (shared_state)
657 return shared_state->get_connections_count();
658 else
659 return {};
660 }
661 virtual void add_used_stripe_peer(const contexts::cryptonote&) override {}
662 virtual void clear_used_stripe_peers() override {}
663 virtual void remove_used_stripe_peer(const contexts::cryptonote&) override {}
664 virtual void for_each_connection(callback_t f) override {
665 if (shared_state)
666 shared_state->foreach_connection([&f](context_t &context){
667 return f(context, context.peer_id, context.support_flags);
668 });
669 }
670 virtual void request_callback(const contexts::basic &context) override {
671 if (shared_state)
672 shared_state->request_callback(context.m_connection_id);
673 }
674 };
675 auto conduct_handshake = [get_conn_tag](net_node_t &net_node, connection_ptr conn){
676 event_t handshaked;
677 net_node.shared_state->for_connection(
678 get_conn_tag(*conn),
679 [&handshaked, &net_node](context_t &context){
680 typename messages::handshake::request msg;
681 net_node.core_protocol->get_payload_sync_data(msg.payload_data);
682 epee::net_utils::async_invoke_remote_command2<typename messages::handshake::response>(
683 context,
684 messages::handshake::ID,
685 msg,
686 *net_node.shared_state,
687 [&handshaked, &net_node](int code, const typename messages::handshake::response &msg, context_t &context){
688 EXPECT_TRUE(code >= 0);
689 net_node.core_protocol->process_payload_sync_data(msg.payload_data, context, true);
690 handshaked.raise();
691 },
692 P2P_DEFAULT_HANDSHAKE_INVOKE_TIMEOUT
693 );
694 return true;
695 }
696 );
697 handshaked.wait();
698 };
699 using path_t = boost::filesystem::path;
700 auto create_dir = []{
701 ec_t ec;
702 path_t path = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("daemon-%%%%%%%%%%%%%%%%", ec);
703 if (ec)
704 return path_t{};
705 auto success = boost::filesystem::create_directory(path, ec);
706 if (not ec && success)
707 return path;
708 return path_t{};
709 };
710 auto remove_tree = [](const path_t &path){
711 ec_t ec;
712 boost::filesystem::remove_all(path, ec);
713 };
714 using options_t = boost::program_options::variables_map;
715 struct daemon_t {
716 options_t options;
717 core_ptr core;
718 core_protocol_ptr core_protocol;
719 net_node_t net_node;
720 shared_state_ptr shared_state;
721 connections_t conn;
722 };
723 struct daemons_t {
724 daemon_t main;
725 daemon_t alt;
726 };
727 using options_description_t = boost::program_options::options_description;
728
729 const auto dir = create_dir();
730 ASSERT_TRUE(not dir.empty());
731
732 daemons_t daemon{
733 {
734 [&dir]{
735 options_t options;
736 boost::program_options::store(
737 boost::program_options::command_line_parser({
738 "--data-dir",
739 (dir / "main").string(),
740 "--disable-dns-checkpoints",
741 "--check-updates=disabled",
742 "--fixed-difficulty=1",
743 "--block-sync-size=1",
744 "--db-sync-mode=fastest:async:50000",
745 }).options([]{
746 options_description_t options_description{};
747 cryptonote::core::init_options(options_description);
748 return options_description;
749 }()).run(),
750 options
751 );
752 return options;
753 }(),
754 {},
755 {},
756 {},
757 {},
758 {},
759 },
760 {
761 [&dir]{
762 options_t options;
763 boost::program_options::store(
764 boost::program_options::command_line_parser({
765 "--data-dir",
766 (dir / "alt").string(),
767 "--disable-dns-checkpoints",
768 "--check-updates=disabled",
769 "--fixed-difficulty=1",
770 "--block-sync-size=1",
771 "--db-sync-mode=fastest:async:50000",
772 }).options([]{
773 options_description_t options_description{};
774 cryptonote::core::init_options(options_description);
775 return options_description;
776 }()).run(),
777 options
778 );
779 return options;
780 }(),
781 {},
782 {},
783 {},
784 {},
785 {},
786 },
787 };
788
789 io_context_t io_context;
790 work_ptr work = std::make_shared<work_t>(io_context.get_executor());
791 workers_t workers;
792 while (workers.size() < 4) {
793 workers.emplace_back([&io_context]{
794 io_context.run();
795 });
796 }
797
798 connection_t::set_rate_up_limit(std::numeric_limits<int64_t>::max());
799 connection_t::set_rate_down_limit(std::numeric_limits<int64_t>::max());
800
801 {
802 daemon.main.core = core_ptr(new core_t(nullptr));
803 daemon.main.core->init(daemon.main.options, nullptr, nullptr);
804 daemon.main.net_node.core_protocol = daemon.main.core_protocol = core_protocol_ptr(new core_protocol_t(
805 *daemon.main.core, &daemon.main.net_node, {}
806 ));
807 daemon.main.core->set_cryptonote_protocol(daemon.main.core_protocol.get());
808 daemon.main.core_protocol->init(daemon.main.options);
809 daemon.main.net_node.shared_state = daemon.main.shared_state = std::make_shared<shared_state_t>();
810 daemon.main.shared_state->set_handler(&daemon.main.net_node);
811 daemon.alt.shared_state = std::make_shared<shared_state_t>();
812 daemon.alt.shared_state->set_handler(&daemon.alt.net_node);
813
814 struct {
815 event_t prepare;
816 event_t check;
817 event_t finish;
818 } events;
819 auto connections = create_conn_pair(
820 connection_ptr(new connection_t(io_context, daemon.main.shared_state, {}, {})),
821 connection_ptr(new connection_t(io_context, daemon.alt.shared_state, {}, {}))
822 );
823 {
824 auto conn = connections.first;
825 auto shared_state = daemon.main.shared_state;
826 const auto tag = get_conn_tag(*conn);
827 boost::asio::post(conn->strand_, [tag, conn, shared_state, &events]{
828 shared_state->for_connection(tag, [](context_t &context){
829 context.m_expect_height = -1;
830 context.m_expect_response = -1;
831 context.m_last_request_time = boost::date_time::min_date_time;
832 context.m_score = 0;
833 context.m_state = contexts::cryptonote::state_synchronizing;
834 return true;
835 });
836 events.prepare.raise();
837 events.check.wait();
838 shared_state->for_connection(tag, [](context_t &context){
839 EXPECT_TRUE(context.m_expect_height == -1);
840 EXPECT_TRUE(context.m_expect_response == -1);
841 EXPECT_TRUE(context.m_last_request_time == boost::date_time::min_date_time);
842 EXPECT_TRUE(context.m_score == 0);
843 EXPECT_TRUE(context.m_state == contexts::cryptonote::state_synchronizing);
844 return true;
845 });
846 events.finish.raise();
847 });
848 }
849 events.prepare.wait();
850 daemon.main.core_protocol->on_idle();
851 events.check.raise();
852 events.finish.wait();
853
854 boost::asio::post(connections.first->strand_, [connections]{
855 connections.first->cancel();
856 });
857 boost::asio::post(connections.second->strand_, [connections]{
858 connections.second->cancel();
859 });
860 connections.first.reset();
861 connections.second.reset();
862 while (daemon.main.shared_state->sock_count);
863 while (daemon.alt.shared_state->sock_count);
864 daemon.main.core_protocol->deinit();
865 daemon.main.core->stop();
866 daemon.main.core->deinit();
867 daemon.main.net_node.shared_state.reset();
868 daemon.main.shared_state.reset();
869 daemon.main.core_protocol.reset();
870 daemon.main.core.reset();
871 daemon.alt.shared_state.reset();
872 }
873
874 {
875 daemon.main.core = core_ptr(new core_t(nullptr));
876 daemon.main.core->init(daemon.main.options, nullptr, nullptr);
877 daemon.main.net_node.core_protocol = daemon.main.core_protocol = core_protocol_ptr(new core_protocol_t(
878 *daemon.main.core, &daemon.main.net_node, {}
879 ));
880 daemon.main.core->set_cryptonote_protocol(daemon.main.core_protocol.get());
881 daemon.main.core->set_checkpoints({});
882 daemon.main.core_protocol->init(daemon.main.options);
883 daemon.main.net_node.shared_state = daemon.main.shared_state = std::make_shared<shared_state_t>();
884 daemon.main.shared_state->set_handler(&daemon.main.net_node);
885 daemon.alt.core = core_ptr(new core_t(nullptr));
886 daemon.alt.core->init(daemon.alt.options, nullptr, nullptr);
887 daemon.alt.net_node.core_protocol = daemon.alt.core_protocol = core_protocol_ptr(new core_protocol_t(
888 *daemon.alt.core, &daemon.alt.net_node, {}
889 ));
890 daemon.alt.core->set_cryptonote_protocol(daemon.alt.core_protocol.get());
891 daemon.alt.core->set_checkpoints({});
892 daemon.alt.core_protocol->init(daemon.alt.options);
893 daemon.alt.net_node.shared_state = daemon.alt.shared_state = std::make_shared<shared_state_t>();
894 daemon.alt.shared_state->set_handler(&daemon.alt.net_node);
895
896 struct {
897 io_context_t io_context;
898 work_ptr work;
899 workers_t workers;
900 } check;
901 check.work = std::make_shared<work_t>(check.io_context.get_executor());
902 while (check.workers.size() < 2) {
903 check.workers.emplace_back([&check]{
904 check.io_context.run();
905 });
906 }
907 while (daemon.main.conn.size() < 1) {
908 daemon.main.conn.emplace_back(new connection_t(check.io_context, daemon.main.shared_state, {}, {}));
909 daemon.alt.conn.emplace_back(new connection_t(io_context, daemon.alt.shared_state, {}, {}));
910 create_conn_pair(daemon.main.conn.back(), daemon.alt.conn.back());
911 conduct_handshake(daemon.alt.net_node, daemon.alt.conn.back());
912 }
913 struct {
914 event_t prepare;
915 event_t sync;
916 event_t finish;
917 } events;
918 {
919 auto conn = daemon.main.conn.back();
920 auto shared_state = daemon.main.shared_state;
921 const auto tag = get_conn_tag(*conn);
922 boost::asio::post(conn->strand_, [tag, conn, shared_state, &events]{
923 shared_state->for_connection(tag, [](context_t &context){
924 EXPECT_TRUE(context.m_state == contexts::cryptonote::state_normal);
925 return true;
926 });
927 events.prepare.raise();
928 events.sync.wait();
929 shared_state->for_connection(tag, [](context_t &context){
930 EXPECT_TRUE(context.m_state == contexts::cryptonote::state_normal);
931 return true;
932 });
933 events.finish.raise();
934 });
935 }
936 events.prepare.wait();
937 daemon.main.core->get_blockchain_storage().add_block_notify(
938 [&events](height_t height, span::blocks blocks){
939 if (height >= CRYPTONOTE_PRUNING_STRIPE_SIZE)
940 events.sync.raise();
941 }
942 );
943 {
944 stat::chain stat{
945 daemon.alt.core->get_blockchain_storage().get_db().get_block_cumulative_difficulty(
946 daemon.alt.core->get_current_blockchain_height() - 1
947 ),
948 daemon.alt.core->get_blockchain_storage().get_db().get_block_already_generated_coins(
949 daemon.alt.core->get_current_blockchain_height() - 1
950 ),
951 };
952 while (daemon.alt.core->get_current_blockchain_height() < CRYPTONOTE_PRUNING_STRIPE_SIZE + CRYPTONOTE_PRUNING_TIP_BLOCKS) {
953 block_t block;
954 diff_t diff;
955 reward_t reward;
956 get_block_template(*daemon.alt.core, block, diff, reward);
957 stat.diff += diff;
958 stat.reward = stat.reward < (MONEY_SUPPLY - stat.reward) ? stat.reward + reward : MONEY_SUPPLY;
959 add_block(*daemon.alt.core, block, stat);
960 if (daemon.main.core->get_current_blockchain_height() + 1 < CRYPTONOTE_PRUNING_STRIPE_SIZE)
961 add_block(*daemon.main.core, block, stat);
962 }
963 }
964 while (daemon.main.conn.size() < 2) {
965 daemon.main.conn.emplace_back(new connection_t(check.io_context, daemon.main.shared_state, {}, {}));
966 daemon.alt.conn.emplace_back(new connection_t(io_context, daemon.alt.shared_state, {}, {}));
967 create_conn_pair(daemon.main.conn.back(), daemon.alt.conn.back());
968 conduct_handshake(daemon.alt.net_node, daemon.alt.conn.back());
969 }
970 events.finish.wait();
971
972 for (;daemon.main.conn.size(); daemon.main.conn.pop_back()) {
973 auto conn = daemon.main.conn.back();
974 boost::asio::post(conn->strand_, [conn]{
975 conn->cancel();
976 });
977 }
978 for (;daemon.alt.conn.size(); daemon.alt.conn.pop_back()) {
979 auto conn = daemon.alt.conn.back();
980 boost::asio::post(conn->strand_, [conn]{
981 conn->cancel();
982 });
983 }
984 while (daemon.main.shared_state->sock_count);
985 while (daemon.alt.shared_state->sock_count);
986 daemon.main.core_protocol->deinit();
987 daemon.main.core->stop();
988 daemon.main.core->deinit();
989 daemon.main.net_node.shared_state.reset();
990 daemon.main.shared_state.reset();
991 daemon.main.core_protocol.reset();
992 daemon.main.core.reset();
993 daemon.alt.core_protocol->deinit();
994 daemon.alt.core->stop();
995 daemon.alt.core->deinit();
996 daemon.alt.net_node.shared_state.reset();
997 daemon.alt.shared_state.reset();
998 daemon.alt.core_protocol.reset();
999 daemon.alt.core.reset();
1000 check.work.reset();
1001 for (auto& w: check.workers) {
1002 w.join();
1003 }
1004 }
1005
1006 work.reset();
1007 for (auto& w: workers) {
1008 w.join();
1009 }
1010 remove_tree(dir);
1011 }
1012
1013 TEST(node_server, race_condition)
1014 {
1015 struct contexts {
1016 using cryptonote = cryptonote::cryptonote_connection_context;
1017 using p2p = nodetool::p2p_connection_context_t<cryptonote>;
1018 };
1019 using context_t = contexts::cryptonote;
1020 using options_t = boost::program_options::variables_map;
1021 using options_description_t = boost::program_options::options_description;
1022 using worker_t = std::thread;
1023 struct protocol_t {
1024 private:
1025 using p2p_endpoint_t = nodetool::i_p2p_endpoint<context_t>;
1026 using lock_t = std::mutex;
1027 using condition_t = std::condition_variable_any;
1028 using unique_lock_t = std::unique_lock<lock_t>;
1029 p2p_endpoint_t *p2p_endpoint;
1030 lock_t lock;
1031 condition_t condition;
1032 bool started{};
1033 size_t counter{};
1034 public:
1035 using payload_t = cryptonote::CORE_SYNC_DATA;
1036 using blob_t = cryptonote::blobdata;
1037 using connection_context = context_t;
1038 using payload_type = payload_t;
1039 using relay_t = cryptonote::relay_method;
1040 using string_t = std::string;
1041 using span_t = epee::span<const uint8_t>;
1042 using blobs_t = epee::span<const cryptonote::blobdata>;
1043 using connections_t = std::list<cryptonote::connection_info>;
1044 using block_queue_t = cryptonote::block_queue;
1045 using stripes_t = std::pair<uint32_t, uint32_t>;
1046 using byte_stream_t = epee::byte_stream;
1047 struct core_events_t: cryptonote::i_core_events {
1048 uint64_t get_current_blockchain_height() const override { return {}; }
1049 bool is_synchronized() const override { return {}; }
1050 void on_transactions_relayed(blobs_t blobs, relay_t relay) override {}
1051 };
1052 int handle_invoke_map(bool is_notify, int command, const span_t in, byte_stream_t &out, context_t &context, bool &handled) {
1053 return {};
1054 }
1055 bool on_idle() {
1056 if (not p2p_endpoint)
1057 return {};
1058 {
1059 unique_lock_t guard(lock);
1060 if (not started)
1061 started = true;
1062 else
1063 return {};
1064 }
1065 std::vector<blob_t> txs(128 / 64 * 1024 * 1024, blob_t(1, 'x'));
1066 worker_t worker([this]{
1067 p2p_endpoint->for_each_connection(
1068 [this](context_t &, uint64_t, uint32_t){
1069 {
1070 unique_lock_t guard(lock);
1071 ++counter;
1072 condition.notify_all();
1073 condition.wait(guard, [this]{ return counter >= 3; });
1074 }
1075 std::this_thread::sleep_for(std::chrono::milliseconds(8));
1076 return false;
1077 }
1078 );
1079 });
1080 {
1081 unique_lock_t guard(lock);
1082 ++counter;
1083 condition.notify_all();
1084 condition.wait(guard, [this]{ return counter >= 3; });
1085 ++counter;
1086 condition.notify_all();
1087 condition.wait(guard, [this]{ return counter >= 5; });
1088 }
1089 p2p_endpoint->send_txs(
1090 std::move(txs),
1091 epee::net_utils::zone::public_,
1092 {},
1093 relay_t::fluff
1094 );
1095 worker.join();
1096 return {};
1097 }
1098 bool init(const options_t &options) { return {}; }
1099 bool deinit() { return {}; }
1100 void set_p2p_endpoint(p2p_endpoint_t *p2p_endpoint) {
1101 this->p2p_endpoint = p2p_endpoint;
1102 }
1103 bool process_payload_sync_data(const payload_t &payload, contexts::p2p &context, bool is_inital) {
1104 context.m_state = context_t::state_normal;
1105 context.m_needed_objects.resize(512 * 1024);
1106 {
1107 unique_lock_t guard(lock);
1108 ++counter;
1109 condition.notify_all();
1110 condition.wait(guard, [this]{ return counter >= 3; });
1111 ++counter;
1112 condition.notify_all();
1113 condition.wait(guard, [this]{ return counter >= 5; });
1114 }
1115 return true;
1116 }
1117 bool get_payload_sync_data(blob_t &blob) { return {}; }
1118 bool get_payload_sync_data(payload_t &payload) { return {}; }
1119 bool on_callback(context_t &context) { return {}; }
1120 core_events_t &get_core(){ static core_events_t core_events; return core_events;}
1121 void log_connections() {}
1122 connections_t get_connections() { return {}; }
1123 const block_queue_t &get_block_queue() const {
1124 static block_queue_t block_queue;
1125 return block_queue;
1126 }
1127 void stop() {}
1128 void on_connection_close(context_t &context) {}
1129 void set_max_out_peers(epee::net_utils::zone zone, unsigned int max) {}
1130 bool no_sync() const { return {}; }
1131 void set_no_sync(bool value) {}
1132 string_t get_peers_overview() const { return {}; }
1133 stripes_t get_next_needed_pruning_stripe() const { return {}; }
1134 bool needs_new_sync_connections(epee::net_utils::zone zone) const { return {}; }
1135 bool is_busy_syncing() { return {}; }
1136 };
1137 using node_server_t = nodetool::node_server<protocol_t>;
1138 auto conduct_test = [](protocol_t &protocol){
1139 struct messages {
1140 struct core {
1141 using sync = cryptonote::CORE_SYNC_DATA;
1142 };
1143 using handshake = nodetool::COMMAND_HANDSHAKE_T<core::sync>;
1144 };
1145 using handler_t = epee::levin::async_protocol_handler<context_t>;
1146 using connection_t = epee::net_utils::connection<handler_t>;
1147 using connection_ptr = boost::shared_ptr<connection_t>;
1148 using shared_state_t = typename connection_t::shared_state;
1149 using shared_state_ptr = std::shared_ptr<shared_state_t>;
1150 using io_context_t = boost::asio::io_context;
1151 using work_t = boost::asio::executor_work_guard<boost::asio::io_context::executor_type>;
1152 using work_ptr = std::shared_ptr<work_t>;
1153 using workers_t = std::vector<std::thread>;
1154 using endpoint_t = boost::asio::ip::tcp::endpoint;
1155 using event_t = epee::simple_event;
1156 struct command_handler_t: epee::levin::levin_commands_handler<context_t> {
1157 using span_t = epee::span<const uint8_t>;
1158 using byte_stream_t = epee::byte_stream;
1159 int invoke(int, const span_t, byte_stream_t &, context_t &) override { return {}; }
1160 int notify(int, const span_t, context_t &) override { return {}; }
1161 void callback(context_t &) override {}
1162 void on_connection_new(context_t &) override {}
1163 void on_connection_close(context_t &) override {}
1164 ~command_handler_t() override {}
1165 static void destroy(epee::levin::levin_commands_handler<context_t>* ptr) { delete ptr; }
1166 };
1167 io_context_t io_context;
1168 work_ptr work = std::make_shared<work_t>(io_context.get_executor());
1169 workers_t workers;
1170 while (workers.size() < 4) {
1171 workers.emplace_back([&io_context]{
1172 io_context.run();
1173 });
1174 }
1175 boost::asio::post(io_context, [&]{
1176 protocol.on_idle();
1177 });
1178 boost::asio::post(io_context, [&]{
1179 protocol.on_idle();
1180 });
1181 shared_state_ptr shared_state = std::make_shared<shared_state_t>();
1182 shared_state->set_handler(new command_handler_t, &command_handler_t::destroy);
1183 connection_ptr conn{new connection_t(io_context, shared_state, {}, {})};
1184 endpoint_t endpoint(boost::asio::ip::make_address("127.0.0.1"), 48080);
1185 conn->socket().connect(endpoint);
1186 conn->socket().set_option(boost::asio::ip::tcp::socket::reuse_address(true));
1187 conn->start({}, {});
1188 context_t context;
1189 conn->get_context(context);
1190 event_t handshaked;
1191 typename messages::handshake::request_t msg{{
1192 ::config::NETWORK_ID,
1193 58080,
1194 }};
1195 epee::net_utils::async_invoke_remote_command2<typename messages::handshake::response>(
1196 context,
1197 messages::handshake::ID,
1198 msg,
1199 *shared_state,
1200 [conn, &handshaked](int code, const typename messages::handshake::response &msg, context_t &context){
1201 EXPECT_TRUE(code >= 0);
1202 handshaked.raise();
1203 },
1204 P2P_DEFAULT_HANDSHAKE_INVOKE_TIMEOUT
1205 );
1206 handshaked.wait();
1207 boost::asio::post(conn->strand_, [conn]{
1208 conn->cancel();
1209 });
1210 conn.reset();
1211 work.reset();
1212 for (auto& w: workers) {
1213 w.join();
1214 }
1215 };
1216 using path_t = boost::filesystem::path;
1217 using ec_t = boost::system::error_code;
1218 auto create_dir = []{
1219 ec_t ec;
1220 path_t path = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("daemon-%%%%%%%%%%%%%%%%", ec);
1221 if (ec)
1222 return path_t{};
1223 auto success = boost::filesystem::create_directory(path, ec);
1224 if (not ec && success)
1225 return path;
1226 return path_t{};
1227 };
1228 auto remove_tree = [](const path_t &path){
1229 ec_t ec;
1230 boost::filesystem::remove_all(path, ec);
1231 };
1232 const auto dir = create_dir();
1233 ASSERT_TRUE(not dir.empty());
1234 protocol_t protocol{};
1235 node_server_t node_server(protocol);
1236 protocol.set_p2p_endpoint(&node_server);
1237 node_server.init(
1238 [&dir]{
1239 options_t options;
1240 boost::program_options::store(
1241 boost::program_options::command_line_parser({
1242 "--p2p-bind-ip=127.0.0.1",
1243 "--p2p-bind-port=48080",
1244 "--out-peers=0",
1245 "--data-dir",
1246 dir.string(),
1247 "--no-igd",
1248 "--add-exclusive-node=127.0.0.1:48080",
1249 "--check-updates=disabled",
1250 "--disable-dns-checkpoints",
1251 }).options([]{
1252 options_description_t options_description{};
1253 cryptonote::core::init_options(options_description);
1254 node_server_t::init_options(options_description);
1255 return options_description;
1256 }()).run(),
1257 options
1258 );
1259 return options;
1260 }()
1261 );
1262 worker_t worker([&]{
1263 node_server.run();
1264 });
1265 conduct_test(protocol);
1266 node_server.send_stop_signal();
1267 worker.join();
1268 node_server.deinit();
1269 remove_tree(dir);
1270 }
1271
1272 namespace nodetool { template class node_server<cryptonote::t_cryptonote_protocol_handler<test_core>>; }
1273 namespace cryptonote { template class t_cryptonote_protocol_handler<test_core>; }