Debian Codegraph @

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