aboutsummaryrefslogblamecommitdiff
path: root/tests/unit_tests/net.cpp
blob: f24ffb45c357b5cb92488f88f122a54efcc9937e (plain) (tree)
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255



























                                                                                          
                    






                                                     
                                      

                                      

                                         

                                      



                                          


                        
              
                 
                      
 
                            


                               
                              




























































































































































































































































































































































































































































































                                                                                                                       

















                                                                                                         





















                                                                                                                   
                                                                                             









































































                                                                                                            

                             


































                                                                                                            

                             






















































                                                                                                 

                                            





























                                                                                      








                                                                                            

                                      
























                                                                                              

                                      























                                                                                              

                                      


























                                                                                              
 

































































































































































































































































































































































































                                                                                                                   
// Copyright (c) 2018, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
//    conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
//    of conditions and the following disclaimer in the documentation and/or other
//    materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
//    used to endorse or promote products derived from this software without specific
//    prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <algorithm>
#include <atomic>
#include <boost/archive/portable_binary_oarchive.hpp>
#include <boost/archive/portable_binary_iarchive.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/asio/write.hpp>
#include <boost/endian/conversion.hpp>
#include <boost/range/adaptor/sliced.hpp>
#include <boost/range/combine.hpp>
#include <boost/system/error_code.hpp>
#include <boost/thread/thread.hpp>
#include <boost/uuid/nil_generator.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid.hpp>
#include <cstdint>
#include <cstring>
#include <functional>
#include <gtest/gtest.h>
#include <map>
#include <memory>
#include <type_traits>

#include "net/dandelionpp.h"
#include "net/error.h"
#include "net/net_utils_base.h"
#include "net/socks.h"
#include "net/socks_connect.h"
#include "net/parse.h"
#include "net/tor_address.h"
#include "p2p/net_peerlist_boost_serialization.h"
#include "serialization/keyvalue_serialization.h"
#include "storages/portable_storage.h"

namespace
{
    static constexpr const char v2_onion[] =
        "xmrto2bturnore26.onion";
    static constexpr const char v3_onion[] =
        "vww6ybal4bd7szmgncyruucpgfkqahzddi37ktceo3ah7ngmcopnpyyd.onion";
}

TEST(tor_address, constants)
{
    static_assert(!net::tor_address::is_local(), "bad is_local() response");
    static_assert(!net::tor_address::is_loopback(), "bad is_loopback() response");
    static_assert(net::tor_address::get_type_id() == epee::net_utils::address_type::tor, "bad get_type_id() response");

    EXPECT_FALSE(net::tor_address::is_local());
    EXPECT_FALSE(net::tor_address::is_loopback());
    EXPECT_EQ(epee::net_utils::address_type::tor, net::tor_address::get_type_id());
    EXPECT_EQ(epee::net_utils::address_type::tor, net::tor_address::get_type_id());
}

TEST(tor_address, invalid)
{
    EXPECT_TRUE(net::tor_address::make("").has_error());
    EXPECT_TRUE(net::tor_address::make(":").has_error());
    EXPECT_TRUE(net::tor_address::make(".onion").has_error());
    EXPECT_TRUE(net::tor_address::make(".onion:").has_error());
    EXPECT_TRUE(net::tor_address::make(v2_onion + 1).has_error());
    EXPECT_TRUE(net::tor_address::make(v3_onion + 1).has_error());
    EXPECT_TRUE(net::tor_address::make(boost::string_ref{v2_onion, sizeof(v2_onion) - 2}).has_error());
    EXPECT_TRUE(net::tor_address::make(boost::string_ref{v3_onion, sizeof(v3_onion) - 2}).has_error());
    EXPECT_TRUE(net::tor_address::make(std::string{v2_onion} + ":-").has_error());
    EXPECT_TRUE(net::tor_address::make(std::string{v2_onion} + ":900a").has_error());
    EXPECT_TRUE(net::tor_address::make(std::string{v3_onion} + ":65536").has_error());
    EXPECT_TRUE(net::tor_address::make(std::string{v3_onion} + ":-1").has_error());

    std::string onion{v3_onion};
    onion.at(10) = 1;
    EXPECT_TRUE(net::tor_address::make(onion).has_error());
}

TEST(tor_address, unblockable_types)
{
    net::tor_address tor{};

    ASSERT_NE(nullptr, tor.host_str());
    EXPECT_STREQ("<unknown tor host>", tor.host_str());
    EXPECT_STREQ("<unknown tor host>", tor.str().c_str());
    EXPECT_EQ(0u, tor.port());
    EXPECT_TRUE(tor.is_unknown());
    EXPECT_FALSE(tor.is_local());
    EXPECT_FALSE(tor.is_loopback());
    EXPECT_EQ(epee::net_utils::address_type::tor, tor.get_type_id());
    EXPECT_EQ(epee::net_utils::zone::tor, tor.get_zone());

    tor = net::tor_address::unknown();
    ASSERT_NE(nullptr, tor.host_str());
    EXPECT_STREQ("<unknown tor host>", tor.host_str());
    EXPECT_STREQ("<unknown tor host>", tor.str().c_str());
    EXPECT_EQ(0u, tor.port());
    EXPECT_TRUE(tor.is_unknown());
    EXPECT_FALSE(tor.is_local());
    EXPECT_FALSE(tor.is_loopback());
    EXPECT_EQ(epee::net_utils::address_type::tor, tor.get_type_id());
    EXPECT_EQ(epee::net_utils::zone::tor, tor.get_zone());

    EXPECT_EQ(net::tor_address{}, net::tor_address::unknown());
}

TEST(tor_address, valid)
{
    const auto address1 = net::tor_address::make(v3_onion);

    ASSERT_TRUE(address1.has_value());
    EXPECT_EQ(0u, address1->port());
    EXPECT_STREQ(v3_onion, address1->host_str());
    EXPECT_STREQ(v3_onion, address1->str().c_str());
    EXPECT_TRUE(address1->is_blockable());

    net::tor_address address2{*address1};

    EXPECT_EQ(0u, address2.port());
    EXPECT_STREQ(v3_onion, address2.host_str());
    EXPECT_STREQ(v3_onion, address2.str().c_str());
    EXPECT_TRUE(address2.is_blockable());
    EXPECT_TRUE(address2.equal(*address1));
    EXPECT_TRUE(address1->equal(address2));
    EXPECT_TRUE(address2 == *address1);
    EXPECT_TRUE(*address1 == address2);
    EXPECT_FALSE(address2 != *address1);
    EXPECT_FALSE(*address1 != address2);
    EXPECT_TRUE(address2.is_same_host(*address1));
    EXPECT_TRUE(address1->is_same_host(address2));
    EXPECT_FALSE(address2.less(*address1));
    EXPECT_FALSE(address1->less(address2));

    address2 = MONERO_UNWRAP(net::tor_address::make(std::string{v2_onion} + ":6545"));

    EXPECT_EQ(6545, address2.port());
    EXPECT_STREQ(v2_onion, address2.host_str());
    EXPECT_EQ(std::string{v2_onion} + ":6545", address2.str().c_str());
    EXPECT_TRUE(address2.is_blockable());
    EXPECT_FALSE(address2.equal(*address1));
    EXPECT_FALSE(address1->equal(address2));
    EXPECT_FALSE(address2 == *address1);
    EXPECT_FALSE(*address1 == address2);
    EXPECT_TRUE(address2 != *address1);
    EXPECT_TRUE(*address1 != address2);
    EXPECT_FALSE(address2.is_same_host(*address1));
    EXPECT_FALSE(address1->is_same_host(address2));
    EXPECT_FALSE(address2.less(*address1));
    EXPECT_TRUE(address1->less(address2));

    address2 = MONERO_UNWRAP(net::tor_address::make(std::string{v3_onion} + ":", 65535));

    EXPECT_EQ(65535, address2.port());
    EXPECT_STREQ(v3_onion, address2.host_str());
    EXPECT_EQ(std::string{v3_onion} + ":65535", address2.str().c_str());
    EXPECT_TRUE(address2.is_blockable());
    EXPECT_FALSE(address2.equal(*address1));
    EXPECT_FALSE(address1->equal(address2));
    EXPECT_FALSE(address2 == *address1);
    EXPECT_FALSE(*address1 == address2);
    EXPECT_TRUE(address2 != *address1);
    EXPECT_TRUE(*address1 != address2);
    EXPECT_TRUE(address2.is_same_host(*address1));
    EXPECT_TRUE(address1->is_same_host(address2));
    EXPECT_FALSE(address2.less(*address1));
    EXPECT_TRUE(address1->less(address2));
}

TEST(tor_address, generic_network_address)
{
    const epee::net_utils::network_address tor1{MONERO_UNWRAP(net::tor_address::make(v3_onion, 8080))};
    const epee::net_utils::network_address tor2{MONERO_UNWRAP(net::tor_address::make(v3_onion, 8080))};
    const epee::net_utils::network_address ip{epee::net_utils::ipv4_network_address{100, 200}};

    EXPECT_EQ(tor1, tor2);
    EXPECT_NE(ip, tor1);
    EXPECT_LT(ip, tor1);

    EXPECT_STREQ(v3_onion, tor1.host_str().c_str());
    EXPECT_EQ(std::string{v3_onion} + ":8080", tor1.str());
    EXPECT_EQ(epee::net_utils::address_type::tor, tor1.get_type_id());
    EXPECT_EQ(epee::net_utils::address_type::tor, tor2.get_type_id());
    EXPECT_EQ(epee::net_utils::address_type::ipv4, ip.get_type_id());
    EXPECT_EQ(epee::net_utils::zone::tor, tor1.get_zone());
    EXPECT_EQ(epee::net_utils::zone::tor, tor2.get_zone());
    EXPECT_EQ(epee::net_utils::zone::public_, ip.get_zone());
    EXPECT_TRUE(tor1.is_blockable());
    EXPECT_TRUE(tor2.is_blockable());
    EXPECT_TRUE(ip.is_blockable());
}

namespace
{
    struct test_command
    {
        net::tor_address tor;

        BEGIN_KV_SERIALIZE_MAP()
            KV_SERIALIZE(tor);
        END_KV_SERIALIZE_MAP()
    };
}

TEST(tor_address, epee_serializev_v2)
{
    std::string buffer{};
    {
        test_command command{MONERO_UNWRAP(net::tor_address::make(v2_onion, 10))};
        EXPECT_FALSE(command.tor.is_unknown());
        EXPECT_NE(net::tor_address{}, command.tor);
        EXPECT_STREQ(v2_onion, command.tor.host_str());
        EXPECT_EQ(10u, command.tor.port());

        epee::serialization::portable_storage stg{};
        EXPECT_TRUE(command.store(stg));
        EXPECT_TRUE(stg.store_to_binary(buffer));
    }

    test_command command{};
    {
        EXPECT_TRUE(command.tor.is_unknown());
        EXPECT_EQ(net::tor_address{}, command.tor);
        EXPECT_STREQ(net::tor_address::unknown_str(), command.tor.host_str());
        EXPECT_EQ(0u, command.tor.port());

        epee::serialization::portable_storage stg{};
        EXPECT_TRUE(stg.load_from_binary(buffer));
        EXPECT_TRUE(command.load(stg));
    }
    EXPECT_FALSE(command.tor.is_unknown());
    EXPECT_NE(net::tor_address{}, command.tor);
    EXPECT_STREQ(v2_onion, command.tor.host_str());
    EXPECT_EQ(10u, command.tor.port());

    // make sure that exceeding max buffer doesn't destroy tor_address::_load
    {
        epee::serialization::portable_storage stg{};
        stg.load_from_binary(buffer);

        std::string host{};
        ASSERT_TRUE(stg.get_value("host", host, stg.open_section("tor", nullptr, false)));
        EXPECT_EQ(std::strlen(v2_onion), host.size());

        host.push_back('k');
        EXPECT_TRUE(stg.set_value("host", host, stg.open_section("tor", nullptr, false)));
        EXPECT_TRUE(command.load(stg)); // poor error reporting from `KV_SERIALIZE`
    }

    EXPECT_TRUE(command.tor.is_unknown());
    EXPECT_EQ(net::tor_address{}, command.tor);
    EXPECT_STREQ(net::tor_address::unknown_str(), command.tor.host_str());
    EXPECT_EQ(0u, command.tor.port());
}

TEST(tor_address, epee_serializev_v3)
{
    std::string buffer{};
    {
        test_command command{MONERO_UNWRAP(net::tor_address::make(v3_onion, 10))};
        EXPECT_FALSE(command.tor.is_unknown());
        EXPECT_NE(net::tor_address{}, command.tor);
        EXPECT_STREQ(v3_onion, command.tor.host_str());
        EXPECT_EQ(10u, command.tor.port());

        epee::serialization::portable_storage stg{};
        EXPECT_TRUE(command.store(stg));
        EXPECT_TRUE(stg.store_to_binary(buffer));
    }

    test_command command{};
    {
        EXPECT_TRUE(command.tor.is_unknown());
        EXPECT_EQ(net::tor_address{}, command.tor);
        EXPECT_STREQ(net::tor_address::unknown_str(), command.tor.host_str());
        EXPECT_EQ(0u, command.tor.port());

        epee::serialization::portable_storage stg{};
        EXPECT_TRUE(stg.load_from_binary(buffer));
        EXPECT_TRUE(command.load(stg));
    }
    EXPECT_FALSE(command.tor.is_unknown());
    EXPECT_NE(net::tor_address{}, command.tor);
    EXPECT_STREQ(v3_onion, command.tor.host_str());
    EXPECT_EQ(10u, command.tor.port());

    // make sure that exceeding max buffer doesn't destroy tor_address::_load
    {
        epee::serialization::portable_storage stg{};
        stg.load_from_binary(buffer);

        std::string host{};
        ASSERT_TRUE(stg.get_value("host", host, stg.open_section("tor", nullptr, false)));
        EXPECT_EQ(std::strlen(v3_onion), host.size());

        host.push_back('k');
        EXPECT_TRUE(stg.set_value("host", host, stg.open_section("tor", nullptr, false)));
        EXPECT_TRUE(command.load(stg)); // poor error reporting from `KV_SERIALIZE`
    }

    EXPECT_TRUE(command.tor.is_unknown());
    EXPECT_EQ(net::tor_address{}, command.tor);
    EXPECT_STRNE(v3_onion, command.tor.host_str());
    EXPECT_EQ(0u, command.tor.port());
}

TEST(tor_address, epee_serialize_unknown)
{
    std::string buffer{};
    {
        test_command command{net::tor_address::unknown()};
        EXPECT_TRUE(command.tor.is_unknown());
        EXPECT_EQ(net::tor_address{}, command.tor);
        EXPECT_STREQ(net::tor_address::unknown_str(), command.tor.host_str());
        EXPECT_EQ(0u, command.tor.port());

        epee::serialization::portable_storage stg{};
        EXPECT_TRUE(command.store(stg));
        EXPECT_TRUE(stg.store_to_binary(buffer));
    }

    test_command command{};
    {
        EXPECT_TRUE(command.tor.is_unknown());
        EXPECT_EQ(net::tor_address{}, command.tor);
        EXPECT_STRNE(v3_onion, command.tor.host_str());
        EXPECT_EQ(0u, command.tor.port());

        epee::serialization::portable_storage stg{};
        EXPECT_TRUE(stg.load_from_binary(buffer));
        EXPECT_TRUE(command.load(stg));
    }
    EXPECT_TRUE(command.tor.is_unknown());
    EXPECT_EQ(net::tor_address{}, command.tor);
    EXPECT_STREQ(net::tor_address::unknown_str(), command.tor.host_str());
    EXPECT_EQ(0u, command.tor.port());

    // make sure that exceeding max buffer doesn't destroy tor_address::_load
    {
        epee::serialization::portable_storage stg{};
        stg.load_from_binary(buffer);

        std::string host{};
        ASSERT_TRUE(stg.get_value("host", host, stg.open_section("tor", nullptr, false)));
        EXPECT_EQ(std::strlen(net::tor_address::unknown_str()), host.size());

        host.push_back('k');
        EXPECT_TRUE(stg.set_value("host", host, stg.open_section("tor", nullptr, false)));
        EXPECT_TRUE(command.load(stg)); // poor error reporting from `KV_SERIALIZE`
    }

    EXPECT_TRUE(command.tor.is_unknown());
    EXPECT_EQ(net::tor_address{}, command.tor);
    EXPECT_STRNE(v3_onion, command.tor.host_str());
    EXPECT_EQ(0u, command.tor.port());
}

TEST(tor_address, boost_serialize_v2)
{
    std::string buffer{};
    {
        const net::tor_address tor = MONERO_UNWRAP(net::tor_address::make(v2_onion, 10));
        EXPECT_FALSE(tor.is_unknown());
        EXPECT_NE(net::tor_address{}, tor);
        EXPECT_STREQ(v2_onion, tor.host_str());
        EXPECT_EQ(10u, tor.port());

        std::ostringstream stream{};
        {
            boost::archive::portable_binary_oarchive archive{stream};
            archive << tor;
        }
        buffer = stream.str();
    }

    net::tor_address tor{};
    {
        EXPECT_TRUE(tor.is_unknown());
        EXPECT_EQ(net::tor_address{}, tor);
        EXPECT_STREQ(net::tor_address::unknown_str(), tor.host_str());
        EXPECT_EQ(0u, tor.port());

        std::istringstream stream{buffer};
        boost::archive::portable_binary_iarchive archive{stream};
        archive >> tor;
    }
    EXPECT_FALSE(tor.is_unknown());
    EXPECT_NE(net::tor_address{}, tor);
    EXPECT_STREQ(v2_onion, tor.host_str());
    EXPECT_EQ(10u, tor.port());
}

TEST(tor_address, boost_serialize_v3)
{
    std::string buffer{};
    {
        const net::tor_address tor = MONERO_UNWRAP(net::tor_address::make(v3_onion, 10));
        EXPECT_FALSE(tor.is_unknown());
        EXPECT_NE(net::tor_address{}, tor);
        EXPECT_STREQ(v3_onion, tor.host_str());
        EXPECT_EQ(10u, tor.port());

        std::ostringstream stream{};
        {
            boost::archive::portable_binary_oarchive archive{stream};
            archive << tor;
        }
        buffer = stream.str();
    }

    net::tor_address tor{};
    {
        EXPECT_TRUE(tor.is_unknown());
        EXPECT_EQ(net::tor_address{}, tor);
        EXPECT_STREQ(net::tor_address::unknown_str(), tor.host_str());
        EXPECT_EQ(0u, tor.port());

        std::istringstream stream{buffer};
        boost::archive::portable_binary_iarchive archive{stream};
        archive >> tor;
    }
    EXPECT_FALSE(tor.is_unknown());
    EXPECT_NE(net::tor_address{}, tor);
    EXPECT_STREQ(v3_onion, tor.host_str());
    EXPECT_EQ(10u, tor.port());
}

TEST(tor_address, boost_serialize_unknown)
{
    std::string buffer{};
    {
        const net::tor_address tor{};
        EXPECT_TRUE(tor.is_unknown());
        EXPECT_EQ(net::tor_address::unknown(), tor);
        EXPECT_STREQ(net::tor_address::unknown_str(), tor.host_str());
        EXPECT_EQ(0u, tor.port());

        std::ostringstream stream{};
        {
            boost::archive::portable_binary_oarchive archive{stream};
            archive << tor;
        }
        buffer = stream.str();
    }

    net::tor_address tor{};
    {
        EXPECT_TRUE(tor.is_unknown());
        EXPECT_EQ(net::tor_address{}, tor);
        EXPECT_STREQ(net::tor_address::unknown_str(), tor.host_str());
        EXPECT_EQ(0u, tor.port());

        std::istringstream stream{buffer};
        boost::archive::portable_binary_iarchive archive{stream};
        archive >> tor;
    }
    EXPECT_TRUE(tor.is_unknown());
    EXPECT_EQ(net::tor_address::unknown(), tor);
    EXPECT_STREQ(net::tor_address::unknown_str(), tor.host_str());
    EXPECT_EQ(0u, tor.port());
}

TEST(get_network_address, onion)
{
    expect<epee::net_utils::network_address> address =
        net::get_network_address("onion", 0);
    EXPECT_EQ(net::error::unsupported_address, address);

    address = net::get_network_address(".onion", 0);
    EXPECT_EQ(net::error::invalid_tor_address, address);

    address = net::get_network_address(v3_onion, 1000);
    ASSERT_TRUE(bool(address));
    EXPECT_EQ(epee::net_utils::address_type::tor, address->get_type_id());
    EXPECT_STREQ(v3_onion, address->host_str().c_str());
    EXPECT_EQ(std::string{v3_onion} + ":1000", address->str());

    address = net::get_network_address(std::string{v3_onion} + ":2000", 1000);
    ASSERT_TRUE(bool(address));
    EXPECT_EQ(epee::net_utils::address_type::tor, address->get_type_id());
    EXPECT_STREQ(v3_onion, address->host_str().c_str());
    EXPECT_EQ(std::string{v3_onion} + ":2000", address->str());

    address = net::get_network_address(std::string{v3_onion} + ":65536", 1000);
    EXPECT_EQ(net::error::invalid_port, address);
}


TEST(get_network_address, ipv4)
{
    expect<epee::net_utils::network_address> address =
        net::get_network_address("0.0.0.", 0);
    EXPECT_EQ(net::error::unsupported_address, address);

    address = net::get_network_address("0.0.0.257", 0);
    EXPECT_EQ(net::error::unsupported_address, address);

    address = net::get_network_address("0.0.0.254", 1000);
    ASSERT_TRUE(bool(address));
    EXPECT_EQ(epee::net_utils::address_type::ipv4, address->get_type_id());
    EXPECT_STREQ("0.0.0.254", address->host_str().c_str());
    EXPECT_STREQ("0.0.0.254:1000", address->str().c_str());

    address = net::get_network_address("23.0.0.254:2000", 1000);
    ASSERT_TRUE(bool(address));
    EXPECT_EQ(epee::net_utils::address_type::ipv4, address->get_type_id());
    EXPECT_STREQ("23.0.0.254", address->host_str().c_str());
    EXPECT_STREQ("23.0.0.254:2000", address->str().c_str());
}

TEST(get_network_address, ipv4subnet)
{
    expect<epee::net_utils::ipv4_network_subnet> address = net::get_ipv4_subnet_address("0.0.0.0", true);
    EXPECT_STREQ("0.0.0.0/32", address->str().c_str());

    address = net::get_ipv4_subnet_address("0.0.0.0");
    EXPECT_TRUE(!address);

    address = net::get_ipv4_subnet_address("0.0.0.0/32");
    EXPECT_STREQ("0.0.0.0/32", address->str().c_str());

    address = net::get_ipv4_subnet_address("0.0.0.0/0");
    EXPECT_STREQ("0.0.0.0/0", address->str().c_str());

    address = net::get_ipv4_subnet_address("12.34.56.78/16");
    EXPECT_STREQ("12.34.0.0/16", address->str().c_str());
}

namespace
{
    using stream_type = boost::asio::ip::tcp;

    struct io_thread
    {
        boost::asio::io_service io_service;
        boost::asio::io_service::work work;
        stream_type::socket server;
        stream_type::acceptor acceptor;
        boost::thread io;
        std::atomic<bool> connected;

        io_thread()
          : io_service(),
            work(io_service),
            server(io_service),
            acceptor(io_service),
            io([this] () { try { this->io_service.run(); } catch (const std::exception& e) { MERROR(e.what()); }}),
            connected(false)
        {
            acceptor.open(boost::asio::ip::tcp::v4());
            acceptor.bind(stream_type::endpoint{boost::asio::ip::address_v4::loopback(), 0});
            acceptor.listen();
            acceptor.async_accept(server, [this] (boost::system::error_code error) {
                this->connected = true;
                if (error)
                    throw boost::system::system_error{error};
            });
        }

        ~io_thread() noexcept
        {
            io_service.stop();
            if (io.joinable())
                io.join();
        }
    };

    struct checked_client
    {
        std::atomic<bool>* called_;
        bool expected_;

        void operator()(boost::system::error_code error, net::socks::client::stream_type::socket&&) const
        {
            EXPECT_EQ(expected_, bool(error)) << "Socks server: " << error.message();
            ASSERT_TRUE(called_ != nullptr);
            (*called_) = true;
        }
    };
}

TEST(socks_client, unsupported_command)
{
    boost::asio::io_service io_service{};
    stream_type::socket client{io_service};

    auto test_client = net::socks::make_connect_client(
        std::move(client), net::socks::version::v4, std::bind( [] {} )
    );
    ASSERT_TRUE(bool(test_client));
    EXPECT_TRUE(test_client->buffer().empty());

    EXPECT_FALSE(test_client->set_connect_command("example.com", 8080));
    EXPECT_TRUE(test_client->buffer().empty());

    EXPECT_FALSE(test_client->set_resolve_command("example.com"));
    EXPECT_TRUE(test_client->buffer().empty());
}

TEST(socks_client, no_command)
{
    boost::asio::io_service io_service{};
    stream_type::socket client{io_service};

    auto test_client = net::socks::make_connect_client(
        std::move(client), net::socks::version::v4a, std::bind( [] {} )
    );
    ASSERT_TRUE(bool(test_client));
    EXPECT_FALSE(net::socks::client::send(std::move(test_client)));
}

TEST(socks_client, connect_command)
{
    io_thread io{};
    stream_type::socket client{io.io_service};

    std::atomic<bool> called{false};
    auto test_client = net::socks::make_connect_client(
        std::move(client), net::socks::version::v4a, checked_client{std::addressof(called), false}
    );
    ASSERT_TRUE(bool(test_client));

    ASSERT_TRUE(test_client->set_connect_command("example.com", 8080));
    EXPECT_FALSE(test_client->buffer().empty());
    ASSERT_TRUE(net::socks::client::connect_and_send(std::move(test_client), io.acceptor.local_endpoint()));
    while (!io.connected)
        ASSERT_FALSE(called);

    const std::uint8_t expected_bytes[] = {
        4, 1, 0x1f, 0x90, 0x00, 0x00, 0x00, 0x01, 0x00,
        'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm', 0x00
    };

    std::uint8_t actual_bytes[sizeof(expected_bytes)];
    boost::asio::read(io.server, boost::asio::buffer(actual_bytes));
    EXPECT_TRUE(std::memcmp(expected_bytes, actual_bytes, sizeof(actual_bytes)) == 0);

    const std::uint8_t reply_bytes[] = {0, 90, 0, 0, 0, 0, 0, 0};
    boost::asio::write(io.server, boost::asio::buffer(reply_bytes));

    // yikes!
    while (!called);
}

TEST(socks_client, connect_command_failed)
{
    io_thread io{};
    stream_type::socket client{io.io_service};

    std::atomic<bool> called{false};
    auto test_client = net::socks::make_connect_client(
        std::move(client), net::socks::version::v4, checked_client{std::addressof(called), true}
    );
    ASSERT_TRUE(bool(test_client));

    ASSERT_TRUE(
        test_client->set_connect_command(
            epee::net_utils::ipv4_network_address{boost::endian::native_to_big(std::uint32_t(5000)), 3000}
        )
    );
    EXPECT_FALSE(test_client->buffer().empty());
    ASSERT_TRUE(net::socks::client::connect_and_send(std::move(test_client), io.acceptor.local_endpoint()));
    while (!io.connected)
        ASSERT_FALSE(called);

    const std::uint8_t expected_bytes[] = {
        4, 1, 0x0b, 0xb8, 0x00, 0x00, 0x13, 0x88, 0x00
    };

    std::uint8_t actual_bytes[sizeof(expected_bytes)];
    boost::asio::read(io.server, boost::asio::buffer(actual_bytes));
    EXPECT_TRUE(std::memcmp(expected_bytes, actual_bytes, sizeof(actual_bytes)) == 0);

    const std::uint8_t reply_bytes[] = {0, 91, 0, 0, 0, 0, 0, 0};
    boost::asio::write(io.server, boost::asio::buffer(reply_bytes));

    // yikes!
    while (!called);
}

TEST(socks_client, resolve_command)
{
    static std::uint8_t reply_bytes[] = {0, 90, 0, 0, 0xff, 0, 0xad, 0};

    struct resolve_client : net::socks::client
    {
        std::atomic<unsigned> called_;
        bool expected_;

        resolve_client(stream_type::socket&& proxy)
          : net::socks::client(std::move(proxy), net::socks::version::v4a_tor)
          , called_(0)
          , expected_(false)
        {};

        virtual void done(boost::system::error_code error, std::shared_ptr<client> self) override
        {
            EXPECT_EQ(this, self.get());
            EXPECT_EQ(expected_, bool(error)) << "Resolve failure: " << error.message();

            if (!error)
            {
                ASSERT_EQ(sizeof(reply_bytes), buffer().size());
                EXPECT_EQ(0u, std::memcmp(buffer().data(), reply_bytes, sizeof(reply_bytes)));
            }

            ++called_;
        }
    };

    io_thread io{};
    stream_type::socket client{io.io_service};

    auto test_client = std::make_shared<resolve_client>(std::move(client));
    ASSERT_TRUE(bool(test_client));

    ASSERT_TRUE(test_client->set_resolve_command("example.com"));
    EXPECT_FALSE(test_client->buffer().empty());
    ASSERT_TRUE(net::socks::client::connect_and_send(test_client, io.acceptor.local_endpoint()));
    while (!io.connected)
        ASSERT_EQ(0u, test_client->called_);

    const std::uint8_t expected_bytes[] = {
        4, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
        'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm', 0x00
    };

    std::uint8_t actual_bytes[sizeof(expected_bytes)];
    boost::asio::read(io.server, boost::asio::buffer(actual_bytes));
    EXPECT_TRUE(std::memcmp(expected_bytes, actual_bytes, sizeof(actual_bytes)) == 0);

    boost::asio::write(io.server, boost::asio::buffer(reply_bytes));

    // yikes!
    while (test_client->called_ == 0);

    test_client->expected_ = true;
    ASSERT_TRUE(test_client->set_resolve_command("example.com"));
    EXPECT_FALSE(test_client->buffer().empty());
    ASSERT_TRUE(net::socks::client::send(test_client));

    boost::asio::read(io.server, boost::asio::buffer(actual_bytes));
    EXPECT_TRUE(std::memcmp(expected_bytes, actual_bytes, sizeof(actual_bytes)) == 0);

    reply_bytes[1] = 91;
    boost::asio::write(io.server, boost::asio::buffer(reply_bytes));

    // yikes!
    while (test_client->called_ == 1);
}

TEST(socks_connector, host)
{
    io_thread io{};
    boost::asio::steady_timer timeout{io.io_service};
    timeout.expires_from_now(std::chrono::seconds{5});

    boost::unique_future<boost::asio::ip::tcp::socket> sock =
        net::socks::connector{io.acceptor.local_endpoint()}("example.com", "8080", timeout);

    while (!io.connected)
        ASSERT_FALSE(sock.is_ready());
    const std::uint8_t expected_bytes[] = {
        4, 1, 0x1f, 0x90, 0x00, 0x00, 0x00, 0x01, 0x00,
        'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm', 0x00
    };

    std::uint8_t actual_bytes[sizeof(expected_bytes)];
    boost::asio::read(io.server, boost::asio::buffer(actual_bytes));
    EXPECT_TRUE(std::memcmp(expected_bytes, actual_bytes, sizeof(actual_bytes)) == 0);

    const std::uint8_t reply_bytes[] = {0, 90, 0, 0, 0, 0, 0, 0};
    boost::asio::write(io.server, boost::asio::buffer(reply_bytes));

    ASSERT_EQ(boost::future_status::ready, sock.wait_for(boost::chrono::seconds{3}));
    EXPECT_TRUE(sock.get().is_open());
}

TEST(socks_connector, ipv4)
{
    io_thread io{};
    boost::asio::steady_timer timeout{io.io_service};
    timeout.expires_from_now(std::chrono::seconds{5});

    boost::unique_future<boost::asio::ip::tcp::socket> sock =
        net::socks::connector{io.acceptor.local_endpoint()}("250.88.125.99", "8080", timeout);

    while (!io.connected)
        ASSERT_FALSE(sock.is_ready());
    const std::uint8_t expected_bytes[] = {
        4, 1, 0x1f, 0x90, 0xfa, 0x58, 0x7d, 0x63, 0x00
    };

    std::uint8_t actual_bytes[sizeof(expected_bytes)];
    boost::asio::read(io.server, boost::asio::buffer(actual_bytes));
    EXPECT_TRUE(std::memcmp(expected_bytes, actual_bytes, sizeof(actual_bytes)) == 0);

    const std::uint8_t reply_bytes[] = {0, 90, 0, 0, 0, 0, 0, 0};
    boost::asio::write(io.server, boost::asio::buffer(reply_bytes));

    ASSERT_EQ(boost::future_status::ready, sock.wait_for(boost::chrono::seconds{3}));
    EXPECT_TRUE(sock.get().is_open());
}

TEST(socks_connector, error)
{
    io_thread io{};
    boost::asio::steady_timer timeout{io.io_service};
    timeout.expires_from_now(std::chrono::seconds{5});

    boost::unique_future<boost::asio::ip::tcp::socket> sock =
        net::socks::connector{io.acceptor.local_endpoint()}("250.88.125.99", "8080", timeout);

    while (!io.connected)
        ASSERT_FALSE(sock.is_ready());
    const std::uint8_t expected_bytes[] = {
        4, 1, 0x1f, 0x90, 0xfa, 0x58, 0x7d, 0x63, 0x00
    };

    std::uint8_t actual_bytes[sizeof(expected_bytes)];
    boost::asio::read(io.server, boost::asio::buffer(actual_bytes));
    EXPECT_TRUE(std::memcmp(expected_bytes, actual_bytes, sizeof(actual_bytes)) == 0);

    const std::uint8_t reply_bytes[] = {0, 91, 0, 0, 0, 0, 0, 0};
    boost::asio::write(io.server, boost::asio::buffer(reply_bytes));

    ASSERT_EQ(boost::future_status::ready, sock.wait_for(boost::chrono::seconds{3}));
    EXPECT_THROW(sock.get().is_open(), boost::system::system_error);
}

TEST(socks_connector, timeout)
{
    io_thread io{};
    boost::asio::steady_timer timeout{io.io_service};
    timeout.expires_from_now(std::chrono::milliseconds{10});

    boost::unique_future<boost::asio::ip::tcp::socket> sock =
        net::socks::connector{io.acceptor.local_endpoint()}("250.88.125.99", "8080", timeout);

    ASSERT_EQ(boost::future_status::ready, sock.wait_for(boost::chrono::seconds{3}));
    EXPECT_THROW(sock.get().is_open(), boost::system::system_error);
}

TEST(dandelionpp_map, traits)
{
    EXPECT_TRUE(std::is_default_constructible<net::dandelionpp::connection_map>());
    EXPECT_TRUE(std::is_move_constructible<net::dandelionpp::connection_map>());
    EXPECT_TRUE(std::is_move_assignable<net::dandelionpp::connection_map>());
    EXPECT_FALSE(std::is_copy_constructible<net::dandelionpp::connection_map>());
    EXPECT_FALSE(std::is_copy_assignable<net::dandelionpp::connection_map>());
}

TEST(dandelionpp_map, empty)
{
    const net::dandelionpp::connection_map mapper{};

    EXPECT_EQ(mapper.begin(), mapper.end());
    EXPECT_EQ(0u, mapper.size());

    const net::dandelionpp::connection_map cloned = mapper.clone();
    EXPECT_EQ(cloned.begin(), cloned.end());
    EXPECT_EQ(0u, cloned.size());
}

TEST(dandelionpp_map, zero_stems)
{
    std::vector<boost::uuids::uuid> connections{6};
    std::generate(connections.begin(), connections.end(), boost::uuids::random_generator{});

    net::dandelionpp::connection_map mapper{connections, 0};
    EXPECT_EQ(mapper.begin(), mapper.end());
    EXPECT_EQ(0u, mapper.size());

    for (const boost::uuids::uuid& connection : connections)
        EXPECT_TRUE(mapper.get_stem(connection).is_nil());

    EXPECT_FALSE(mapper.update(connections));
    EXPECT_EQ(mapper.begin(), mapper.end());
    EXPECT_EQ(0u, mapper.size());

    for (const boost::uuids::uuid& connection : connections)
        EXPECT_TRUE(mapper.get_stem(connection).is_nil());

    const net::dandelionpp::connection_map cloned = mapper.clone();
    EXPECT_EQ(cloned.end(), cloned.begin());
    EXPECT_EQ(0u, cloned.size());
}

TEST(dandelionpp_map, dropped_connection)
{
    std::vector<boost::uuids::uuid> connections{6};
    std::generate(connections.begin(), connections.end(), boost::uuids::random_generator{});
    std::sort(connections.begin(), connections.end());

    // select 3 of 6 outgoing connections
    net::dandelionpp::connection_map mapper{connections, 3};
    EXPECT_EQ(3u, mapper.size());
    EXPECT_EQ(3, mapper.end() - mapper.begin());
    {
        std::set<boost::uuids::uuid> used;
        for (const boost::uuids::uuid& connection : mapper)
        {
            EXPECT_TRUE(used.insert(connection).second);
            EXPECT_TRUE(std::binary_search(connections.begin(), connections.end(), connection));
        }
    }
    {
        const net::dandelionpp::connection_map cloned = mapper.clone();
        EXPECT_EQ(3u, cloned.size());
        ASSERT_EQ(mapper.end() - mapper.begin(), cloned.end() - cloned.begin());
        for (auto elem : boost::combine(mapper, cloned))
            EXPECT_EQ(boost::get<0>(elem), boost::get<1>(elem));
    }
    EXPECT_FALSE(mapper.update(connections));
    EXPECT_EQ(3u, mapper.size());
    ASSERT_EQ(3, mapper.end() - mapper.begin());
    {
        std::set<boost::uuids::uuid> used;
        for (const boost::uuids::uuid& connection : mapper)
        {
            EXPECT_FALSE(connection.is_nil());
            EXPECT_TRUE(used.insert(connection).second);
            EXPECT_TRUE(std::binary_search(connections.begin(), connections.end(), connection));
        }
    }
    std::map<boost::uuids::uuid, boost::uuids::uuid> mapping;
    std::vector<boost::uuids::uuid> in_connections{9};
    std::generate(in_connections.begin(), in_connections.end(), boost::uuids::random_generator{});
    {
        std::map<boost::uuids::uuid, std::size_t> used;
        std::multimap<boost::uuids::uuid, boost::uuids::uuid> inverse_mapping;
        for (const boost::uuids::uuid& connection : in_connections)
        {
            const boost::uuids::uuid out = mapper.get_stem(connection);
            EXPECT_FALSE(out.is_nil());
            EXPECT_TRUE(mapping.emplace(connection, out).second);
            inverse_mapping.emplace(out, connection);
            used[out]++;
        }

        EXPECT_EQ(3u, used.size());
        for (const std::pair<boost::uuids::uuid, std::size_t>& entry : used)
            EXPECT_EQ(3u, entry.second);

        for (const boost::uuids::uuid& connection : in_connections)
            EXPECT_EQ(mapping[connection], mapper.get_stem(connection));

        // drop 1 connection, and select replacement from 1 of unused 3.
        const boost::uuids::uuid lost_connection = *(++mapper.begin());
        const auto elem = std::lower_bound(connections.begin(), connections.end(), lost_connection);
        ASSERT_NE(connections.end(), elem);
        ASSERT_EQ(lost_connection, *elem);
        connections.erase(elem);

        EXPECT_TRUE(mapper.update(connections));
        EXPECT_EQ(3u, mapper.size());
        ASSERT_EQ(3, mapper.end() - mapper.begin());

        for (const boost::uuids::uuid& connection : mapper)
        {
            EXPECT_FALSE(connection.is_nil());
            EXPECT_NE(lost_connection, connection);
        }

        const boost::uuids::uuid newly_mapped = *(++mapper.begin());
        EXPECT_FALSE(newly_mapped.is_nil());
        EXPECT_NE(lost_connection, newly_mapped);

        for (auto elems = inverse_mapping.equal_range(lost_connection); elems.first != elems.second; ++elems.first)
            mapping[elems.first->second] = newly_mapped;
    }
    {
        const net::dandelionpp::connection_map cloned = mapper.clone();
        EXPECT_EQ(3u, cloned.size());
        ASSERT_EQ(mapper.end() - mapper.begin(), cloned.end() - cloned.begin());
        for (auto elem : boost::combine(mapper, cloned))
            EXPECT_EQ(boost::get<0>(elem), boost::get<1>(elem));
    }
    // mappings should remain evenly distributed amongst 2, with 3 sitting in waiting
    {
        std::set<boost::uuids::uuid> used;
        for (const boost::uuids::uuid& connection : mapper)
        {
            EXPECT_FALSE(connection.is_nil());
            EXPECT_TRUE(used.insert(connection).second);
            EXPECT_TRUE(std::binary_search(connections.begin(), connections.end(), connection));
        }
    }
    {
        std::map<boost::uuids::uuid, std::size_t> used;
        for (const boost::uuids::uuid& connection : in_connections)
        {
            const boost::uuids::uuid& out = mapper.get_stem(connection);
            EXPECT_FALSE(out.is_nil());
            EXPECT_EQ(mapping[connection], out);
            used[out]++;
        }

        EXPECT_EQ(3u, used.size());
        for (const std::pair<boost::uuids::uuid, std::size_t>& entry : used)
            EXPECT_EQ(3u, entry.second);
    }
    {
        const net::dandelionpp::connection_map cloned = mapper.clone();
        EXPECT_EQ(3u, cloned.size());
        ASSERT_EQ(mapper.end() - mapper.begin(), cloned.end() - cloned.begin());
        for (auto elem : boost::combine(mapper, cloned))
            EXPECT_EQ(boost::get<0>(elem), boost::get<1>(elem));
    }
}

TEST(dandelionpp_map, dropped_connection_remapped)
{
    boost::uuids::random_generator random_uuid{};

    std::vector<boost::uuids::uuid> connections{3};
    std::generate(connections.begin(), connections.end(), random_uuid);
    std::sort(connections.begin(), connections.end());

    // select 3 of 3 outgoing connections
    net::dandelionpp::connection_map mapper{connections, 3};
    EXPECT_EQ(3u, mapper.size());
    EXPECT_EQ(3, mapper.end() - mapper.begin());
    {
        std::set<boost::uuids::uuid> used;
        for (const boost::uuids::uuid& connection : mapper)
        {
            EXPECT_FALSE(connection.is_nil());
            EXPECT_TRUE(used.insert(connection).second);
            EXPECT_TRUE(std::binary_search(connections.begin(), connections.end(), connection));
        }
    }
    EXPECT_FALSE(mapper.update(connections));
    EXPECT_EQ(3u, mapper.size());
    ASSERT_EQ(3, mapper.end() - mapper.begin());
    {
        std::set<boost::uuids::uuid> used;
        for (const boost::uuids::uuid& connection : mapper)
        {
            EXPECT_FALSE(connection.is_nil());
            EXPECT_TRUE(used.insert(connection).second);
            EXPECT_TRUE(std::binary_search(connections.begin(), connections.end(), connection));
        }
    }
    std::map<boost::uuids::uuid, boost::uuids::uuid> mapping;
    std::vector<boost::uuids::uuid> in_connections{9};
    std::generate(in_connections.begin(), in_connections.end(), random_uuid);
    {
        std::map<boost::uuids::uuid, std::size_t> used;
        std::multimap<boost::uuids::uuid, boost::uuids::uuid> inverse_mapping;
        for (const boost::uuids::uuid& connection : in_connections)
        {
            const boost::uuids::uuid out = mapper.get_stem(connection);
            EXPECT_FALSE(out.is_nil());
            EXPECT_TRUE(mapping.emplace(connection, out).second);
            inverse_mapping.emplace(out, connection);
            used[out]++;
        }

        EXPECT_EQ(3u, used.size());
        for (const std::pair<boost::uuids::uuid, std::size_t>& entry : used)
            EXPECT_EQ(3u, entry.second);

        for (const boost::uuids::uuid& connection : in_connections)
            EXPECT_EQ(mapping[connection], mapper.get_stem(connection));

        // drop 1 connection leaving "hole"
        const boost::uuids::uuid lost_connection = *(++mapper.begin());
        const auto elem = std::lower_bound(connections.begin(), connections.end(), lost_connection);
        ASSERT_NE(connections.end(), elem);
        ASSERT_EQ(lost_connection, *elem);
        connections.erase(elem);

        EXPECT_TRUE(mapper.update(connections));
        EXPECT_EQ(2u, mapper.size());
        EXPECT_EQ(3, mapper.end() - mapper.begin());

        for (auto elems = inverse_mapping.equal_range(lost_connection); elems.first != elems.second; ++elems.first)
            mapping[elems.first->second] = boost::uuids::nil_uuid();
    }
    // remap 3 connections and map 1 new connection to 2 remaining out connections
    in_connections.resize(10);
    in_connections[9] = random_uuid();
    {
        std::map<boost::uuids::uuid, std::size_t> used;
        for (const boost::uuids::uuid& connection : in_connections)
        {
            const boost::uuids::uuid& out = mapper.get_stem(connection);
            EXPECT_FALSE(out.is_nil());
            used[out]++;

            boost::uuids::uuid& expected = mapping[connection];
            if (!expected.is_nil())
                EXPECT_EQ(expected, out);
            else
                expected = out;
        }

        EXPECT_EQ(2u, used.size());
        for (const std::pair<boost::uuids::uuid, std::size_t>& entry : used)
            EXPECT_EQ(5u, entry.second);
    }
    // select 3 of 3 connections but do not remap existing links
    connections.resize(3);
    connections[2] = random_uuid();
    EXPECT_TRUE(mapper.update(connections));
    EXPECT_EQ(3u, mapper.size());
    EXPECT_EQ(3, mapper.end() - mapper.begin());
    {
        std::map<boost::uuids::uuid, std::size_t> used;
        for (const boost::uuids::uuid& connection : in_connections)
        {
            const boost::uuids::uuid& out = mapper.get_stem(connection);
            EXPECT_FALSE(out.is_nil());
            used[out]++;

            EXPECT_EQ(mapping[connection], out);
        }

        EXPECT_EQ(2u, used.size());
        for (const std::pair<boost::uuids::uuid, std::size_t>& entry : used)
            EXPECT_EQ(5u, entry.second);
    }
    // map 8 new incoming connections across 3 outgoing links
    in_connections.resize(18);
    std::generate(in_connections.begin() + 10, in_connections.end(), random_uuid);
    {
        std::map<boost::uuids::uuid, std::size_t> used;
        for (const boost::uuids::uuid& connection : in_connections)
        {
            const boost::uuids::uuid& out = mapper.get_stem(connection);
            EXPECT_FALSE(out.is_nil());
            used[out]++;

            boost::uuids::uuid& expected = mapping[connection];
            if (!expected.is_nil())
                EXPECT_EQ(expected, out);
            else
                expected = out;
        }

        EXPECT_EQ(3u, used.size());
        for (const std::pair<boost::uuids::uuid, std::size_t>& entry : used)
            EXPECT_EQ(6u, entry.second);
    }
}

TEST(dandelionpp_map, dropped_all_connections)
{
    boost::uuids::random_generator random_uuid{};

    std::vector<boost::uuids::uuid> connections{8};
    std::generate(connections.begin(), connections.end(), random_uuid);
    std::sort(connections.begin(), connections.end());

    // select 3 of 8 outgoing connections
    net::dandelionpp::connection_map mapper{connections, 3};
    EXPECT_EQ(3u, mapper.size());
    EXPECT_EQ(3, mapper.end() - mapper.begin());
    {
        std::set<boost::uuids::uuid> used;
        for (const boost::uuids::uuid& connection : mapper)
        {
            EXPECT_FALSE(connection.is_nil());
            EXPECT_TRUE(used.insert(connection).second);
            EXPECT_TRUE(std::binary_search(connections.begin(), connections.end(), connection));
        }
    }
    EXPECT_FALSE(mapper.update(connections));
    EXPECT_EQ(3u, mapper.size());
    ASSERT_EQ(3, mapper.end() - mapper.begin());
    {
        std::set<boost::uuids::uuid> used;
        for (const boost::uuids::uuid& connection : mapper)
        {
            EXPECT_FALSE(connection.is_nil());
            EXPECT_TRUE(used.insert(connection).second);
            EXPECT_TRUE(std::binary_search(connections.begin(), connections.end(), connection));
        }
    }
    std::vector<boost::uuids::uuid> in_connections{9};
    std::generate(in_connections.begin(), in_connections.end(), random_uuid);
    {
        std::map<boost::uuids::uuid, std::size_t> used;
        std::map<boost::uuids::uuid, boost::uuids::uuid> mapping;
        for (const boost::uuids::uuid& connection : in_connections)
        {
            const boost::uuids::uuid out = mapper.get_stem(connection);
            EXPECT_FALSE(out.is_nil());
            EXPECT_TRUE(mapping.emplace(connection, out).second);
            used[out]++;
        }

        EXPECT_EQ(3u, used.size());
        for (const std::pair<boost::uuids::uuid, std::size_t>& entry : used)
            EXPECT_EQ(3u, entry.second);

        for (const boost::uuids::uuid& connection : in_connections)
            EXPECT_EQ(mapping[connection], mapper.get_stem(connection));

        // drop all connections
        connections.clear();

        EXPECT_TRUE(mapper.update(connections));
        EXPECT_EQ(0u, mapper.size());
        EXPECT_EQ(3, mapper.end() - mapper.begin());
    }
    // remap 7 connections to nothing
    for (const boost::uuids::uuid& connection : boost::adaptors::slice(in_connections, 0, 7))
        EXPECT_TRUE(mapper.get_stem(connection).is_nil());

    // select 3 of 30 connections, only 7 should be remapped to new indexes (but all to new uuids)
    connections.resize(30);
    std::generate(connections.begin(), connections.end(), random_uuid);
    EXPECT_TRUE(mapper.update(connections));
    {
        std::map<boost::uuids::uuid, std::size_t> used;
        for (const boost::uuids::uuid& connection : in_connections)
        {
            const boost::uuids::uuid& out = mapper.get_stem(connection);
            EXPECT_FALSE(out.is_nil());
            used[out]++;
        }

        EXPECT_EQ(3u, used.size());
        for (const std::pair<boost::uuids::uuid, std::size_t>& entry : used)
            EXPECT_EQ(3u, entry.second);
    }
}