File: Destination.cpp

package info (click to toggle)
i2pd 2.58.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,612 kB
  • sloc: cpp: 59,663; makefile: 224; sh: 138
file content (1666 lines) | stat: -rw-r--r-- 57,349 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
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
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
/*
* Copyright (c) 2013-2025, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/

#include <algorithm>
#include <cassert>
#include <string>
#include <set>
#include <vector>
#include <charconv>
#include <boost/algorithm/string.hpp>
#include "Crypto.h"
#include "ECIESX25519AEADRatchetSession.h"
#include "Log.h"
#include "FS.h"
#include "Timestamp.h"
#include "NetDb.hpp"
#include "Destination.h"

namespace i2p
{
namespace client
{
	LeaseSetDestination::LeaseSetDestination (boost::asio::io_context& service,
		bool isPublic, const std::map<std::string, std::string> * params):
		m_Service (service), m_IsPublic (isPublic), m_PublishReplyToken (0),
		m_LastSubmissionTime (0), m_PublishConfirmationTimer (m_Service),
		m_PublishVerificationTimer (m_Service), m_PublishDelayTimer (m_Service), m_CleanupTimer (m_Service),
		m_LeaseSetType (DEFAULT_LEASESET_TYPE), m_AuthType (i2p::data::ENCRYPTED_LEASESET_AUTH_TYPE_NONE)
	{
		int inLen   = DEFAULT_INBOUND_TUNNEL_LENGTH;
		int inQty   = DEFAULT_INBOUND_TUNNELS_QUANTITY;
		int outLen  = DEFAULT_OUTBOUND_TUNNEL_LENGTH;
		int outQty  = DEFAULT_OUTBOUND_TUNNELS_QUANTITY;
		int inVar   = DEFAULT_INBOUND_TUNNELS_LENGTH_VARIANCE;
		int outVar  = DEFAULT_OUTBOUND_TUNNELS_LENGTH_VARIANCE;
		int numTags = DEFAULT_TAGS_TO_SEND;
		bool isHighBandwidth = true;
		std::shared_ptr<std::vector<i2p::data::IdentHash> > explicitPeers;
		try
		{
			if (params)
			{
				auto it = params->find (I2CP_PARAM_INBOUND_TUNNEL_LENGTH);
				if (it != params->end ())
					inLen = std::stoi(it->second);
				it = params->find (I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH);
				if (it != params->end ())
					outLen = std::stoi(it->second);
				it = params->find (I2CP_PARAM_INBOUND_TUNNELS_QUANTITY);
				if (it != params->end ())
					inQty = std::stoi(it->second);
				it = params->find (I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY);
				if (it != params->end ())
					outQty = std::stoi(it->second);
				it = params->find (I2CP_PARAM_INBOUND_TUNNELS_LENGTH_VARIANCE);
				if (it != params->end ())
					inVar = std::stoi(it->second);
				it = params->find (I2CP_PARAM_OUTBOUND_TUNNELS_LENGTH_VARIANCE);
				if (it != params->end ())
					outVar = std::stoi(it->second);
				it = params->find (I2CP_PARAM_TAGS_TO_SEND);
				if (it != params->end ())
					numTags = std::stoi(it->second);
				LogPrint (eLogInfo, "Destination: Parameters for tunnel set to: ", inQty, " inbound (", inLen, " hops), ", outQty, " outbound (", outLen, " hops), ", numTags, " tags");
				it = params->find (I2CP_PARAM_RATCHET_INBOUND_TAGS);
				if (it != params->end ())
					SetNumRatchetInboundTags (std::stoi(it->second));
				it = params->find (I2CP_PARAM_EXPLICIT_PEERS);
				if (it != params->end ())
				{
					explicitPeers = std::make_shared<std::vector<i2p::data::IdentHash> >();
					std::stringstream ss(it->second);
					std::string b64;
					while (std::getline (ss, b64, ','))
					{
						i2p::data::IdentHash ident;
						ident.FromBase64 (b64);
						explicitPeers->push_back (ident);
						LogPrint (eLogInfo, "Destination: Added to explicit peers list: ", b64);
					}
				}
				it = params->find (I2CP_PARAM_INBOUND_NICKNAME);
				if (it != params->end ()) m_Nickname = it->second;
				else // try outbound
				{
					it = params->find (I2CP_PARAM_OUTBOUND_NICKNAME);
					if (it != params->end ()) m_Nickname = it->second;
					// otherwise we set default nickname in Start when we know local address
				}
				it = params->find (I2CP_PARAM_DONT_PUBLISH_LEASESET);
				if (it != params->end ())
					// override isPublic
					m_IsPublic = GetBoolParamValue (it->second);
				it = params->find (I2CP_PARAM_LEASESET_TYPE);
				if (it != params->end ())
					m_LeaseSetType = std::stoi(it->second);
				if (m_LeaseSetType == i2p::data::NETDB_STORE_TYPE_ENCRYPTED_LEASESET2)
				{
					// authentication for encrypted LeaseSet
					it = params->find (I2CP_PARAM_LEASESET_AUTH_TYPE);
					if (it != params->end ())
					{
						auto authType = std::stoi (it->second);
						if (authType >= i2p::data::ENCRYPTED_LEASESET_AUTH_TYPE_NONE && authType <= i2p::data::ENCRYPTED_LEASESET_AUTH_TYPE_PSK)
							m_AuthType = authType;
						else
							LogPrint (eLogError, "Destination: Unknown auth type: ", authType);
					}
				}
				it = params->find (I2CP_PARAM_LEASESET_PRIV_KEY);
				if (it != params->end ())
				{
					m_LeaseSetPrivKey.reset (new i2p::data::Tag<32>());
					if (m_LeaseSetPrivKey->FromBase64 (it->second) != 32)
					{
						LogPrint(eLogCritical, "Destination: Invalid value i2cp.leaseSetPrivKey: ", it->second);
						m_LeaseSetPrivKey.reset (nullptr);
					}
				}
				it = params->find (I2CP_PARAM_STREAMING_PROFILE);
				if (it != params->end ())
					isHighBandwidth = std::stoi (it->second) != STREAMING_PROFILE_INTERACTIVE;
			}
		}
		catch (std::exception & ex)
		{
			LogPrint(eLogError, "Destination: Unable to parse parameters for destination: ", ex.what());
		}
		SetNumTags (numTags);
		m_Pool = i2p::tunnel::tunnels.CreateTunnelPool (inLen, outLen, inQty, outQty, inVar, outVar, isHighBandwidth);
		if (explicitPeers)
			m_Pool->SetExplicitPeers (explicitPeers);
		if(params)
		{
			auto itr = params->find(I2CP_PARAM_MAX_TUNNEL_LATENCY);
			if (itr != params->end()) {
				auto maxlatency = std::stoi(itr->second);
				itr = params->find(I2CP_PARAM_MIN_TUNNEL_LATENCY);
				if (itr != params->end()) {
					auto minlatency = std::stoi(itr->second);
					if ( minlatency > 0 && maxlatency > 0 ) {
						// set tunnel pool latency
						LogPrint(eLogInfo, "Destination: Requiring tunnel latency [", minlatency, "ms, ", maxlatency, "ms]");
						m_Pool->RequireLatency(minlatency, maxlatency);
					}
				}
			}
		}
	}

	LeaseSetDestination::~LeaseSetDestination ()
	{
		if (m_Pool)
			i2p::tunnel::tunnels.DeleteTunnelPool (m_Pool);
		for (auto& it: m_LeaseSetRequests)
			it.second->Complete (nullptr);
	}

	void LeaseSetDestination::Start ()
	{
		if (m_Nickname.empty ())
			m_Nickname = i2p::data::GetIdentHashAbbreviation (GetIdentHash ()); // set default nickname
		LoadTags ();
		m_Pool->SetLocalDestination (shared_from_this ());
		m_Pool->SetActive (true);
		m_CleanupTimer.expires_from_now (boost::posix_time::seconds (DESTINATION_CLEANUP_TIMEOUT));
		m_CleanupTimer.async_wait (std::bind (&LeaseSetDestination::HandleCleanupTimer,
			shared_from_this (), std::placeholders::_1));
	}

	void LeaseSetDestination::Stop ()
	{
		m_CleanupTimer.cancel ();
		m_PublishConfirmationTimer.cancel ();
		m_PublishVerificationTimer.cancel ();
		if (m_Pool)
		{
			m_Pool->SetLocalDestination (nullptr);
			i2p::tunnel::tunnels.StopTunnelPool (m_Pool);
		}
		SaveTags ();
		CleanUp (); // GarlicDestination
	}

	bool LeaseSetDestination::GetBoolParamValue (std::string_view value)
	{
		bool ret = false;
		if (value == "true") 
			ret = true;
		else if (value == "false") 
			ret = false;
		else
		{
			int v = 0;
			auto res = std::from_chars(value.data(), value.data() + value.size(), v);
			if (res.ec != std::errc())	
				LogPrint (eLogError, "Destination: Unable to parse bool param value ", value, ": ",  std::make_error_code (res.ec).message ());
			ret = v;		
		}	
		return ret;
	}	
		
	bool LeaseSetDestination::Reconfigure(std::map<std::string, std::string> params)
	{
		auto itr = params.find("i2cp.dontPublishLeaseSet");
		if (itr != params.end())
		{
			m_IsPublic = itr->second != "true";
		}

		int inLen = 0, outLen = 0, inQuant = 0, outQuant = 0, numTags = 0, minLatency = 0, maxLatency = 0;
		std::map<std::string, int&> intOpts = {
			{I2CP_PARAM_INBOUND_TUNNEL_LENGTH, inLen},
			{I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH, outLen},
			{I2CP_PARAM_INBOUND_TUNNELS_QUANTITY, inQuant},
			{I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY, outQuant},
			{I2CP_PARAM_TAGS_TO_SEND, numTags},
			{I2CP_PARAM_MIN_TUNNEL_LATENCY, minLatency},
			{I2CP_PARAM_MAX_TUNNEL_LATENCY, maxLatency}
		};

		auto pool = GetTunnelPool();
		inLen = pool->GetNumInboundHops();
		outLen = pool->GetNumOutboundHops();
		inQuant = pool->GetNumInboundTunnels();
		outQuant = pool->GetNumOutboundTunnels();
		minLatency = 0;
		maxLatency = 0;

		for (auto & opt : intOpts)
		{
			itr = params.find(opt.first);
			if(itr != params.end())
			{
				opt.second = std::stoi(itr->second);
			}
		}
		pool->RequireLatency(minLatency, maxLatency);
		return pool->Reconfigure(inLen, outLen, inQuant, outQuant);
	}

	std::shared_ptr<i2p::data::LeaseSet> LeaseSetDestination::FindLeaseSet (const i2p::data::IdentHash& ident)
	{
		std::shared_ptr<i2p::data::LeaseSet> remoteLS;
		{
			std::lock_guard<std::mutex> lock(m_RemoteLeaseSetsMutex);
			auto it = m_RemoteLeaseSets.find (ident);
			if (it != m_RemoteLeaseSets.end ())
				remoteLS = it->second;
		}

		if (remoteLS)
		{
			if (!remoteLS->IsExpired ())
			{
				if (remoteLS->ExpiresSoon())
				{
					LogPrint(eLogDebug, "Destination: Lease Set expires soon, updating before expire");
					// update now before expiration for smooth handover
					auto s = shared_from_this ();
					RequestDestination(ident, [s, ident] (std::shared_ptr<i2p::data::LeaseSet> ls) {
						if(ls && !ls->IsExpired())
						{
							ls->PopulateLeases();
							{
								std::lock_guard<std::mutex> _lock(s->m_RemoteLeaseSetsMutex);
								s->m_RemoteLeaseSets[ident] = ls;
							}
						}
					});
				}
				return remoteLS;
			}
			else
			{
				LogPrint (eLogWarning, "Destination: Remote LeaseSet expired");
				std::lock_guard<std::mutex> lock(m_RemoteLeaseSetsMutex);
				m_RemoteLeaseSets.erase (ident);
				return nullptr;
			}
		}
		return nullptr;
	}

	std::shared_ptr<const i2p::data::LocalLeaseSet> LeaseSetDestination::GetLeaseSet ()
	{
		if (!m_Pool) return nullptr;
		if (!m_LeaseSet)
			UpdateLeaseSet ();
		auto ls = GetLeaseSetMt ();
		return (ls && ls->GetInnerLeaseSet ()) ? ls->GetInnerLeaseSet () : ls; // always non-encrypted
	}

	std::shared_ptr<const i2p::data::LocalLeaseSet> LeaseSetDestination::GetLeaseSetMt ()
	{
		std::lock_guard<std::mutex> l(m_LeaseSetMutex);
		return m_LeaseSet;
	}

	void LeaseSetDestination::SetLeaseSet (std::shared_ptr<const i2p::data::LocalLeaseSet> newLeaseSet)
	{
		{
			std::lock_guard<std::mutex> l(m_LeaseSetMutex);
			m_LeaseSet = newLeaseSet;
		}
		i2p::garlic::GarlicDestination::SetLeaseSetUpdated ();
		if (m_IsPublic)
		{
			auto s = shared_from_this ();
			boost::asio::post (m_Service, [s](void)
			{
				s->m_PublishVerificationTimer.cancel ();
				s->Publish ();
			});
		}
	}

	void LeaseSetDestination::UpdateLeaseSet ()
	{
		int numTunnels = m_Pool->GetNumInboundTunnels () + 2; // 2 backup tunnels
		if (numTunnels > i2p::data::MAX_NUM_LEASES) numTunnels = i2p::data::MAX_NUM_LEASES; // 16 tunnels maximum
		auto tunnels = m_Pool->GetInboundTunnels (numTunnels);
		if (!tunnels.empty ())
			CreateNewLeaseSet (tunnels);
		else
			LogPrint (eLogInfo, "Destination: No inbound tunnels for LeaseSet");
	}

	bool LeaseSetDestination::SubmitSessionKey (const uint8_t * key, const uint8_t * tag)
	{
		struct
		{
			uint8_t k[32], t[32];
		} data;
		memcpy (data.k, key, 32);
		memcpy (data.t, tag, 32);
		auto s = shared_from_this ();
		boost::asio::post (m_Service, [s,data](void)
			{
				s->AddSessionKey (data.k, data.t);
			});
		return true;
	}

	void LeaseSetDestination::SubmitECIESx25519Key (const uint8_t * key, uint64_t tag)
	{
		struct
		{
			uint8_t k[32];
			uint64_t t;
		} data;
		memcpy (data.k, key, 32);
		data.t = tag;
		auto s = shared_from_this ();
		boost::asio::post (m_Service, [s,data](void)
			{
				s->AddECIESx25519Key (data.k, data.t);
			});
	}

	void LeaseSetDestination::ProcessGarlicMessage (std::shared_ptr<I2NPMessage> msg)
	{
		if (!msg) return;
		bool empty = false;
		{
			std::lock_guard<std::mutex> l(m_IncomingMsgsQueueMutex);
			empty = m_IncomingMsgsQueue.empty ();
			m_IncomingMsgsQueue.push_back (msg);
		}
		if (empty)
			boost::asio::post (m_Service, [s = shared_from_this ()]() 
			{ 
				std::list<std::shared_ptr<I2NPMessage> > receivedMsgs;
				{
					std::lock_guard<std::mutex> l(s->m_IncomingMsgsQueueMutex);
					s->m_IncomingMsgsQueue.swap (receivedMsgs);
				}
			    for (auto& it: receivedMsgs)
			    	s->HandleGarlicMessage (it);               
			});
	}

	void LeaseSetDestination::ProcessDeliveryStatusMessage (std::shared_ptr<I2NPMessage> msg)
	{
		uint32_t msgID = bufbe32toh (msg->GetPayload () + DELIVERY_STATUS_MSGID_OFFSET);
		boost::asio::post (m_Service, std::bind (&LeaseSetDestination::HandleDeliveryStatusMessage, shared_from_this (), msgID));
	}

	void LeaseSetDestination::HandleI2NPMessage (const uint8_t * buf, size_t len)
	{
		I2NPMessageType typeID = (I2NPMessageType)(buf[I2NP_HEADER_TYPEID_OFFSET]);
		uint32_t msgID = bufbe32toh (buf + I2NP_HEADER_MSGID_OFFSET);
		LeaseSetDestination::HandleCloveI2NPMessage (typeID, buf + I2NP_HEADER_SIZE, 
			GetI2NPMessageLength(buf, len) - I2NP_HEADER_SIZE, msgID, nullptr);
	}

	bool LeaseSetDestination::HandleCloveI2NPMessage (I2NPMessageType typeID, const uint8_t * payload,
		size_t len, uint32_t msgID, i2p::garlic::ECIESX25519AEADRatchetSession * from)
	{
		switch (typeID)
		{
			case eI2NPData:
				HandleDataMessage (payload, len, from);
			break;
			case eI2NPDeliveryStatus:
				HandleDeliveryStatusMessage (bufbe32toh (payload + DELIVERY_STATUS_MSGID_OFFSET));
			break;
			case eI2NPTunnelTest:
				if (m_Pool)
					m_Pool->ProcessTunnelTest (bufbe32toh (payload + TUNNEL_TEST_MSGID_OFFSET), bufbe64toh (payload + TUNNEL_TEST_TIMESTAMP_OFFSET));
			break;
			case eI2NPDatabaseStore:
				HandleDatabaseStoreMessage (payload, len, from);
			break;
			case eI2NPDatabaseSearchReply:
				HandleDatabaseSearchReplyMessage (payload, len);
			break;
			case eI2NPShortTunnelBuildReply: // might come as garlic encrypted
				i2p::HandleI2NPMessage (CreateI2NPMessage (typeID, payload, len, msgID));
			break;
			default:
				LogPrint (eLogWarning, "Destination: Unexpected I2NP message type ", typeID);
				return false;
		}
		return true;
	}

	void LeaseSetDestination::HandleDatabaseStoreMessage (const uint8_t * buf, size_t len,
		i2p::garlic::ECIESX25519AEADRatchetSession * from)
	{
		if (len < DATABASE_STORE_HEADER_SIZE)
		{
			LogPrint (eLogError, "Destination: Database store msg is too short ", len);
			return;
		}
		uint32_t replyToken = bufbe32toh (buf + DATABASE_STORE_REPLY_TOKEN_OFFSET);
		size_t offset = DATABASE_STORE_HEADER_SIZE;
		if (replyToken)
		{
			LogPrint (eLogInfo, "Destination: Reply token is ignored for DatabaseStore");
			offset += 36;
		}
		if (offset > len || len > i2p::data::MAX_LS_BUFFER_SIZE + offset)
		{
			LogPrint (eLogError, "Destination: Database store message is too long ", len);
			return;
		}
		i2p::data::IdentHash key (buf + DATABASE_STORE_KEY_OFFSET);
		std::shared_ptr<i2p::data::LeaseSet> leaseSet;
		std::shared_ptr<LeaseSetRequest> request;
		switch (buf[DATABASE_STORE_TYPE_OFFSET])
		{
			case i2p::data::NETDB_STORE_TYPE_LEASESET: // 1
			case i2p::data::NETDB_STORE_TYPE_STANDARD_LEASESET2: // 3
			{
				LogPrint (eLogDebug, "Destination: Remote LeaseSet");
				std::lock_guard<std::mutex> lock(m_RemoteLeaseSetsMutex);
				auto it = m_RemoteLeaseSets.find (key);
				if (it != m_RemoteLeaseSets.end () &&
					it->second->GetStoreType () == buf[DATABASE_STORE_TYPE_OFFSET]) // update only if same type
				{
					leaseSet = it->second;
					if (leaseSet->IsNewer (buf + offset, len - offset))
					{
						leaseSet->Update (buf + offset, len - offset, shared_from_this(), true);
						if (leaseSet->IsValid () && leaseSet->GetIdentHash () == key && !leaseSet->IsExpired ())
							LogPrint (eLogDebug, "Destination: Remote LeaseSet updated");
						else
						{
							LogPrint (eLogDebug, "Destination: Remote LeaseSet update failed");
							m_RemoteLeaseSets.erase (it);
							leaseSet = nullptr;
						}
					}
					else
						LogPrint (eLogDebug, "Destination: Remote LeaseSet is older. Not updated");
				}
				else
				{
					// add or replace
					if (buf[DATABASE_STORE_TYPE_OFFSET] == i2p::data::NETDB_STORE_TYPE_LEASESET)
						leaseSet = std::make_shared<i2p::data::LeaseSet> (buf + offset, len - offset); // LeaseSet
					else
					{	
						leaseSet = std::make_shared<i2p::data::LeaseSet2> (buf[DATABASE_STORE_TYPE_OFFSET], 
							buf + offset, len - offset, true, shared_from_this (), 
						    from ? from->GetRemoteStaticKeyType () : GetPreferredCryptoType () ); // LeaseSet2
						if (from)
						{
							uint8_t pub[32];
							leaseSet->Encrypt (nullptr, pub);
							if (memcmp (from->GetRemoteStaticKey (), pub, 32))
							{
								LogPrint (eLogError, "Destination: Remote LeaseSet static key mismatch");
								leaseSet = nullptr;
							}	
						}	
					}		
					if (leaseSet && leaseSet->IsValid () && leaseSet->GetIdentHash () == key && !leaseSet->IsExpired ())
					{
						if (leaseSet->GetIdentHash () != GetIdentHash ())
						{
							LogPrint (eLogDebug, "Destination: New remote LeaseSet added");
							m_RemoteLeaseSets.insert_or_assign (key, leaseSet);
							if (from)
								from->SetDestination (key);
						}
						else
							LogPrint (eLogDebug, "Destination: Own remote LeaseSet dropped");
					}
					else
					{
						LogPrint (eLogError, "Destination: New remote LeaseSet failed");
						leaseSet = nullptr;
					}
				}
				break;
			}
			case i2p::data::NETDB_STORE_TYPE_ENCRYPTED_LEASESET2: // 5
			{
				auto it2 = m_LeaseSetRequests.find (key);
				if (it2 != m_LeaseSetRequests.end ())
				{
					request = it2->second;
					m_LeaseSetRequests.erase (it2);
					if (request->requestedBlindedKey)
					{
						auto ls2 = std::make_shared<i2p::data::LeaseSet2> (buf + offset, len - offset,
							request->requestedBlindedKey, shared_from_this (), 
						    m_LeaseSetPrivKey ? ((const uint8_t *)*m_LeaseSetPrivKey) : nullptr, GetPreferredCryptoType ());
						if (ls2->IsValid () && !ls2->IsExpired ())
						{
							leaseSet = ls2;
							std::lock_guard<std::mutex> lock(m_RemoteLeaseSetsMutex);
							m_RemoteLeaseSets[ls2->GetIdentHash ()] = ls2; // ident is not key
							m_RemoteLeaseSets[key] = ls2; // also store as key for next lookup
						}
						else
							LogPrint (eLogError, "Destination: New remote encrypted LeaseSet2 failed");
					}
					else
					{
						// publishing verification doesn't have requestedBlindedKey
						auto localLeaseSet = GetLeaseSetMt ();
						if (localLeaseSet->GetStoreHash () == key)
						{
							auto ls = std::make_shared<i2p::data::LeaseSet2> (i2p::data::NETDB_STORE_TYPE_ENCRYPTED_LEASESET2,
								localLeaseSet->GetBuffer (), localLeaseSet->GetBufferLen (), false);
							leaseSet = ls;
						}
						else
							LogPrint (eLogWarning, "Destination: Encrypted LeaseSet2 received for request without blinded key");
					}
				}
				else
					LogPrint (eLogWarning, "Destination: Couldn't find request for encrypted LeaseSet2");
				break;
			}
			default:
				LogPrint (eLogError, "Destination: Unexpected client's DatabaseStore type ", buf[DATABASE_STORE_TYPE_OFFSET], ", dropped");
		}

		if (!request)
		{
			auto it1 = m_LeaseSetRequests.find (key);
			if (it1 != m_LeaseSetRequests.end ())
			{
				request = it1->second;
				m_LeaseSetRequests.erase (it1);
			}
		}
		if (request)
		{
			request->requestTimeoutTimer.cancel ();
			request->Complete (leaseSet);
		}
	}

	void LeaseSetDestination::HandleDatabaseSearchReplyMessage (const uint8_t * buf, size_t len)
	{
		i2p::data::IdentHash key (buf);
		int num = buf[32]; // num
		LogPrint (eLogDebug, "Destination: DatabaseSearchReply for ", key.ToBase64 (), " num=", num);
		auto it = m_LeaseSetRequests.find (key);
		if (it != m_LeaseSetRequests.end ())
		{
			auto request = it->second;
			for (int i = 0; i < num; i++)
			{
				i2p::data::IdentHash peerHash (buf + 33 + i*32);
				if (!request->excluded.count (peerHash) && !i2p::data::netdb.FindRouter (peerHash))
				{
					LogPrint (eLogInfo, "Destination: Found new floodfill, request it");
					i2p::data::netdb.RequestDestination (peerHash, nullptr, false); // through exploratory
				}
			}
			SendNextLeaseSetRequest (key, request);
		}
		else
			LogPrint (eLogWarning, "Destination: Request for ", key.ToBase64 (), " not found");
	}

	void LeaseSetDestination::SendNextLeaseSetRequest (const i2p::data::IdentHash& key,
		std::shared_ptr<LeaseSetRequest> request)
	{
		bool found = false;
		if (request->excluded.size () < MAX_NUM_FLOODFILLS_PER_REQUEST)
		{
			auto floodfill = i2p::data::netdb.GetClosestFloodfill (key, request->excluded);
			if (floodfill)
			{
				LogPrint (eLogInfo, "Destination: Requesting ", key.ToBase64 (), " at ", floodfill->GetIdentHash ().ToBase64 ());
				if (SendLeaseSetRequest (key, floodfill, request))
					found = true;
			}
		}
		if (!found)
		{
			LogPrint (eLogInfo, "Destination: ", key.ToBase64 (), " was not found on ", MAX_NUM_FLOODFILLS_PER_REQUEST, " floodfills");
			request->Complete (nullptr);
			m_LeaseSetRequests.erase (key);
		}
	}

	void LeaseSetDestination::HandleDeliveryStatusMessage (uint32_t msgID)
	{
		if (msgID == m_PublishReplyToken)
		{
			LogPrint (eLogDebug, "Destination: Publishing LeaseSet confirmed for ", GetIdentHash().ToBase32());
			m_ExcludedFloodfills.clear ();
			m_PublishReplyToken = 0;
			// schedule verification
			m_PublishVerificationTimer.expires_from_now (boost::posix_time::seconds(PUBLISH_VERIFICATION_TIMEOUT +
				(m_Pool ? m_Pool->GetRng ()() % PUBLISH_VERIFICATION_TIMEOUT_VARIANCE : 0)));
			m_PublishVerificationTimer.async_wait (std::bind (&LeaseSetDestination::HandlePublishVerificationTimer,
			shared_from_this (), std::placeholders::_1));
		}
		else
			i2p::garlic::GarlicDestination::HandleDeliveryStatusMessage (msgID);
	}

	void LeaseSetDestination::SetLeaseSetUpdated (bool post)
	{
		if (post)
			boost::asio::post (m_Service, [s = shared_from_this ()]() { s->UpdateLeaseSet (); });
		else
			UpdateLeaseSet ();
	}

	void LeaseSetDestination::Publish ()
	{
		auto leaseSet = GetLeaseSetMt ();
		if (!leaseSet || !m_Pool)
		{
			LogPrint (eLogError, "Destination: Can't publish non-existing LeaseSet");
			return;
		}
		if (m_PublishReplyToken)
		{
			LogPrint (eLogDebug, "Destination: Publishing LeaseSet is pending");
			return;
		}
		auto ts = i2p::util::GetSecondsSinceEpoch ();
		if (ts < m_LastSubmissionTime + PUBLISH_MIN_INTERVAL)
		{
			LogPrint (eLogDebug, "Destination: Publishing LeaseSet is too fast. Wait for ", PUBLISH_MIN_INTERVAL, " seconds");
			m_PublishDelayTimer.cancel ();
			m_PublishDelayTimer.expires_from_now (boost::posix_time::seconds(PUBLISH_MIN_INTERVAL));
			m_PublishDelayTimer.async_wait (std::bind (&LeaseSetDestination::HandlePublishDelayTimer,
				shared_from_this (), std::placeholders::_1));
			return;
		}
		auto floodfill = i2p::data::netdb.GetClosestFloodfill (leaseSet->GetStoreHash (), m_ExcludedFloodfills);
		if (!floodfill)
		{
			LogPrint (eLogError, "Destination: Can't publish LeaseSet, no more floodfills found");
			m_ExcludedFloodfills.clear ();
			return;
		}
		auto outbound = m_Pool->GetNextOutboundTunnel (nullptr, floodfill->GetCompatibleTransports (false));
		auto inbound = m_Pool->GetNextInboundTunnel (nullptr, floodfill->GetCompatibleTransports (true));
		if (!outbound || !inbound)
		{
			if (!m_Pool->GetInboundTunnels ().empty () && !m_Pool->GetOutboundTunnels ().empty ())
			{
				LogPrint (eLogInfo, "Destination: No compatible tunnels with ", floodfill->GetIdentHash ().ToBase64 (), ". Trying another floodfill");
				m_ExcludedFloodfills.insert (floodfill->GetIdentHash ());
				floodfill = i2p::data::netdb.GetClosestFloodfill (leaseSet->GetStoreHash (), m_ExcludedFloodfills);
				if (floodfill)
				{
					outbound = m_Pool->GetNextOutboundTunnel (nullptr, floodfill->GetCompatibleTransports (false));
					if (outbound)
					{
						inbound = m_Pool->GetNextInboundTunnel (nullptr, floodfill->GetCompatibleTransports (true));
						if (!inbound)
							LogPrint (eLogError, "Destination: Can't publish LeaseSet. No inbound tunnels");
					}
					else
						LogPrint (eLogError, "Destination: Can't publish LeaseSet. No outbound tunnels");
				}
				else
					LogPrint (eLogError, "Destination: Can't publish LeaseSet, no more floodfills found");
			}
			else
				LogPrint (eLogDebug, "Destination: No tunnels in pool");

			if (!floodfill || !outbound || !inbound)
			{
				// we can't publish now
				m_ExcludedFloodfills.clear ();
				m_PublishReplyToken = 1; // dummy non-zero value
				// try again after a while
				LogPrint (eLogInfo, "Destination: Can't publish LeasetSet because destination is not ready. Try publishing again after ", PUBLISH_CONFIRMATION_TIMEOUT, " milliseconds");
				m_PublishConfirmationTimer.expires_from_now (boost::posix_time::milliseconds(PUBLISH_CONFIRMATION_TIMEOUT));
				m_PublishConfirmationTimer.async_wait (std::bind (&LeaseSetDestination::HandlePublishConfirmationTimer,
					shared_from_this (), std::placeholders::_1));
				return;
			}
		}
		m_ExcludedFloodfills.insert (floodfill->GetIdentHash ());
		LogPrint (eLogDebug, "Destination: Publish LeaseSet of ", GetIdentHash ().ToBase32 ());
		RAND_bytes ((uint8_t *)&m_PublishReplyToken, 4);
		auto msg = WrapMessageForRouter (floodfill, i2p::CreateDatabaseStoreMsg (leaseSet, m_PublishReplyToken, inbound));
		auto s = shared_from_this ();
		msg->onDrop = [s]()
			{
				boost::asio::post (s->GetService (), [s]()
					{
						s->m_PublishConfirmationTimer.cancel ();
						s->HandlePublishConfirmationTimer (boost::system::error_code());
					});
			};
		m_PublishConfirmationTimer.expires_from_now (boost::posix_time::milliseconds(PUBLISH_CONFIRMATION_TIMEOUT));
		m_PublishConfirmationTimer.async_wait (std::bind (&LeaseSetDestination::HandlePublishConfirmationTimer,
			shared_from_this (), std::placeholders::_1));
		outbound->SendTunnelDataMsgTo (floodfill->GetIdentHash (), 0, msg);
		m_LastSubmissionTime = ts;
	}

	void LeaseSetDestination::HandlePublishConfirmationTimer (const boost::system::error_code& ecode)
	{
		if (ecode != boost::asio::error::operation_aborted)
		{
			if (m_PublishReplyToken)
			{
				LogPrint (eLogWarning, "Destination: Publish confirmation was not received in ", PUBLISH_CONFIRMATION_TIMEOUT, " milliseconds or failed. will try again");
				m_PublishReplyToken = 0;
				Publish ();
			}
		}
	}

	void LeaseSetDestination::HandlePublishVerificationTimer (const boost::system::error_code& ecode)
	{
		if (ecode != boost::asio::error::operation_aborted)
		{
			auto ls = GetLeaseSetMt ();
			if (!ls)
			{
				LogPrint (eLogWarning, "Destination: Couldn't verify LeaseSet for ", GetIdentHash().ToBase32());
				return;
			}
			auto s = shared_from_this ();
			RequestLeaseSet (ls->GetStoreHash (),
				[s, ls](std::shared_ptr<const i2p::data::LeaseSet> leaseSet)
				{
					if (leaseSet)
					{
						if (*ls == *leaseSet)
						{
							// we got latest LeasetSet
							LogPrint (eLogDebug, "Destination: Published LeaseSet verified for ", s->GetIdentHash().ToBase32());
							s->m_PublishVerificationTimer.expires_from_now (boost::posix_time::seconds(PUBLISH_REGULAR_VERIFICATION_INTERNAL));
							s->m_PublishVerificationTimer.async_wait (std::bind (&LeaseSetDestination::HandlePublishVerificationTimer, s, std::placeholders::_1));
							return;
						}
						else
							LogPrint (eLogDebug, "Destination: LeaseSet is different than just published for ", s->GetIdentHash().ToBase32());
					}
					else
						LogPrint (eLogWarning, "Destination: Couldn't find published LeaseSet for ", s->GetIdentHash().ToBase32());
					// we have to publish again
					s->Publish ();
				});
		}
	}

	void LeaseSetDestination::HandlePublishDelayTimer (const boost::system::error_code& ecode)
	{
		if (ecode != boost::asio::error::operation_aborted)
			Publish ();
	}

	bool LeaseSetDestination::RequestDestination (const i2p::data::IdentHash& dest, RequestComplete requestComplete)
	{
		if (!m_Pool || !IsReady ())
		{
			if (requestComplete)
				boost::asio::post (m_Service, [requestComplete](void){requestComplete (nullptr);});
			return false;
		}
		boost::asio::post (m_Service, std::bind (&LeaseSetDestination::RequestLeaseSet, shared_from_this (), dest, requestComplete, nullptr));
		return true;
	}

	bool LeaseSetDestination::RequestDestinationWithEncryptedLeaseSet (std::shared_ptr<const i2p::data::BlindedPublicKey> dest, RequestComplete requestComplete)
	{
		if (!dest || !m_Pool || !IsReady ())
		{
			if (requestComplete)
				boost::asio::post (m_Service, [requestComplete](void){requestComplete (nullptr);});
			return false;
		}
		auto storeHash = dest->GetStoreHash ();
		auto leaseSet = FindLeaseSet (storeHash);
		if (leaseSet)
		{
			if (requestComplete)
				boost::asio::post (m_Service, [requestComplete, leaseSet](void){requestComplete (leaseSet);});
			return true;
		}
		boost::asio::post (m_Service, std::bind (&LeaseSetDestination::RequestLeaseSet, shared_from_this (), storeHash, requestComplete, dest));
		return true;
	}

	void LeaseSetDestination::CancelDestinationRequest (const i2p::data::IdentHash& dest, bool notify)
	{
		auto s = shared_from_this ();
		boost::asio::post (m_Service, [dest, notify, s](void)
			{
				auto it = s->m_LeaseSetRequests.find (dest);
				if (it != s->m_LeaseSetRequests.end ())
				{
					auto requestComplete = it->second;
					s->m_LeaseSetRequests.erase (it);
					if (notify && requestComplete) requestComplete->Complete (nullptr);
				}
			});
	}

	void LeaseSetDestination::CancelDestinationRequestWithEncryptedLeaseSet (std::shared_ptr<const i2p::data::BlindedPublicKey> dest, bool notify)
	{
		if (dest)
			CancelDestinationRequest (dest->GetStoreHash (), notify);
	}

	void LeaseSetDestination::RequestLeaseSet (const i2p::data::IdentHash& dest, RequestComplete requestComplete, std::shared_ptr<const i2p::data::BlindedPublicKey> requestedBlindedKey)
	{
		std::unordered_set<i2p::data::IdentHash> excluded;
		auto floodfill = i2p::data::netdb.GetClosestFloodfill (dest, excluded);
		if (floodfill)
		{
			auto request = std::make_shared<LeaseSetRequest> (m_Service);
			request->requestedBlindedKey = requestedBlindedKey; // for encrypted LeaseSet2
			if (requestComplete)
				request->requestComplete.push_back (requestComplete);
			auto ts = i2p::util::GetMillisecondsSinceEpoch ();
			auto ret = m_LeaseSetRequests.insert (std::pair<i2p::data::IdentHash, std::shared_ptr<LeaseSetRequest> >(dest,request));
			if (ret.second) // inserted
			{
				request->requestTime = ts;
				if (!SendLeaseSetRequest (dest, floodfill, request))
				{
					// try another
					LogPrint (eLogWarning, "Destination: Couldn't send LeaseSet request to ", floodfill->GetIdentHash ().ToBase64 (), ". Trying another");
					request->excluded.insert (floodfill->GetIdentHash ());
					floodfill = i2p::data::netdb.GetClosestFloodfill (dest, request->excluded);
					if (!SendLeaseSetRequest (dest, floodfill, request))
					{
						// request failed
						LogPrint (eLogWarning, "Destination: LeaseSet request for ", dest.ToBase32 (), " was not sent");
						m_LeaseSetRequests.erase (ret.first);
						if (requestComplete) requestComplete (nullptr);
					}
				}
			}
			else // duplicate
			{
				LogPrint (eLogInfo, "Destination: Request of LeaseSet ", dest.ToBase64 (), " is pending already");
				if (ts > ret.first->second->requestTime + MAX_LEASESET_REQUEST_TIMEOUT)
				{
					// something went wrong
					m_LeaseSetRequests.erase (ret.first);
					if (requestComplete) requestComplete (nullptr);
				}
				else if (requestComplete)
					ret.first->second->requestComplete.push_back (requestComplete);
			}
		}
		else
		{
			LogPrint (eLogError, "Destination: Can't request LeaseSet, no floodfills found");
			if (requestComplete) requestComplete (nullptr);
		}
	}

	bool LeaseSetDestination::SendLeaseSetRequest (const i2p::data::IdentHash& dest,
		std::shared_ptr<const i2p::data::RouterInfo> nextFloodfill, std::shared_ptr<LeaseSetRequest> request)
	{
		if (!request->replyTunnel || !request->replyTunnel->IsEstablished ())
			request->replyTunnel = m_Pool->GetNextInboundTunnel (nullptr, nextFloodfill->GetCompatibleTransports (false)); // outbound from floodfill
		if (!request->replyTunnel) LogPrint (eLogWarning, "Destination: Can't send LeaseSet request, no compatible inbound tunnels found");
		if (!request->outboundTunnel || !request->outboundTunnel->IsEstablished ())
			request->outboundTunnel = m_Pool->GetNextOutboundTunnel (nullptr, nextFloodfill->GetCompatibleTransports (true)); // inbound from floodfill
		if (!request->outboundTunnel) LogPrint (eLogWarning, "Destination: Can't send LeaseSet request, no compatible outbound tunnels found");

		if (request->replyTunnel && request->outboundTunnel)
		{
			request->excluded.insert (nextFloodfill->GetIdentHash ());
			request->requestTimeoutTimer.cancel ();

			bool isECIES = SupportsEncryptionType (i2p::data::CRYPTO_KEY_TYPE_ECIES_X25519_AEAD) &&
				nextFloodfill->GetVersion () >= MAKE_VERSION_NUMBER(0, 9, 46); // >= 0.9.46;
			uint8_t replyKey[32], replyTag[32];
			RAND_bytes (replyKey, 32); // random session key
			RAND_bytes (replyTag, isECIES ? 8 : 32); // random session tag
			if (isECIES)
				AddECIESx25519Key (replyKey, replyTag);
			else
				AddSessionKey (replyKey, replyTag);

			auto msg = WrapMessageForRouter (nextFloodfill,
				CreateLeaseSetDatabaseLookupMsg (dest, request->excluded, request->replyTunnel, replyKey, replyTag, isECIES));
			auto s = shared_from_this ();
			msg->onDrop = [s, dest, request]()
				{
					boost::asio::post (s->GetService (), [s, dest, request]()
						{
							s->SendNextLeaseSetRequest (dest, request);
						});
				};
			request->outboundTunnel->SendTunnelDataMsgs (
				{
					i2p::tunnel::TunnelMessageBlock
					{
						i2p::tunnel::eDeliveryTypeRouter,
						nextFloodfill->GetIdentHash (), 0, msg
					}
				});
			request->requestTimeoutTimer.expires_from_now (boost::posix_time::milliseconds(LEASESET_REQUEST_TIMEOUT));
			request->requestTimeoutTimer.async_wait (std::bind (&LeaseSetDestination::HandleRequestTimoutTimer,
				shared_from_this (), std::placeholders::_1, dest));
		}
		else
			return false;
		return true;
	}

	void LeaseSetDestination::HandleRequestTimoutTimer (const boost::system::error_code& ecode, const i2p::data::IdentHash& dest)
	{
		if (ecode != boost::asio::error::operation_aborted)
		{
			auto it = m_LeaseSetRequests.find (dest);
			if (it != m_LeaseSetRequests.end ())
			{
				bool done = false;
				uint64_t ts = i2p::util::GetMillisecondsSinceEpoch ();
				if (ts < it->second->requestTime + MAX_LEASESET_REQUEST_TIMEOUT)
				{
					auto floodfill = i2p::data::netdb.GetClosestFloodfill (dest, it->second->excluded);
					if (floodfill)
					{
						// reset tunnels, because one them might fail
						it->second->outboundTunnel = nullptr;
						it->second->replyTunnel = nullptr;
						done = !SendLeaseSetRequest (dest, floodfill, it->second);
					}
					else
						done = true;
				}
				else
				{
					LogPrint (eLogWarning, "Destination: ", dest.ToBase64 (), " was not found within ", MAX_LEASESET_REQUEST_TIMEOUT, " seconds");
					done = true;
				}

				if (done)
				{
					auto requestComplete = it->second;
					m_LeaseSetRequests.erase (it);
					if (requestComplete) requestComplete->Complete (nullptr);
				}
			}
		}
	}

	void LeaseSetDestination::HandleCleanupTimer (const boost::system::error_code& ecode)
	{
		if (ecode != boost::asio::error::operation_aborted)
		{
			CleanupExpiredTags ();
			CleanupRemoteLeaseSets ();
			CleanupDestination ();
			m_CleanupTimer.expires_from_now (boost::posix_time::seconds (DESTINATION_CLEANUP_TIMEOUT +
				(m_Pool ? m_Pool->GetRng ()() % DESTINATION_CLEANUP_TIMEOUT_VARIANCE : 0)));
			m_CleanupTimer.async_wait (std::bind (&LeaseSetDestination::HandleCleanupTimer,
				shared_from_this (), std::placeholders::_1));
		}
	}

	void LeaseSetDestination::CleanupRemoteLeaseSets ()
	{
		auto ts = i2p::util::GetMillisecondsSinceEpoch ();
		std::lock_guard<std::mutex> lock(m_RemoteLeaseSetsMutex);
		for (auto it = m_RemoteLeaseSets.begin (); it != m_RemoteLeaseSets.end ();)
		{
			if (it->second->IsEmpty () || ts > it->second->GetExpirationTime ()) // leaseset expired
			{
				LogPrint (eLogDebug, "Destination: Remote LeaseSet ", it->second->GetIdentHash ().ToBase64 (), " expired");
				it = m_RemoteLeaseSets.erase (it);
			}
			else
				++it;
		}
	}

	ClientDestination::ClientDestination (boost::asio::io_context& service, const i2p::data::PrivateKeys& keys,
		bool isPublic, const std::map<std::string, std::string> * params):
		LeaseSetDestination (service, isPublic, params),
		m_Keys (keys), m_PreferredCryptoType (0), m_StreamingAckDelay (DEFAULT_INITIAL_ACK_DELAY),
		m_StreamingOutboundSpeed (DEFAULT_MAX_OUTBOUND_SPEED),
		m_StreamingInboundSpeed (DEFAULT_MAX_INBOUND_SPEED),
		m_StreamingMaxConcurrentStreams (DEFAULT_MAX_CONCURRENT_STREAMS),
		m_StreamingMaxWindowSize (i2p::stream::MAX_WINDOW_SIZE),
		m_IsStreamingAnswerPings (DEFAULT_ANSWER_PINGS), m_IsStreamingDontSign (DEFAULT_DONT_SIGN), 
		m_LastPort (0), m_DatagramDestination (nullptr), m_RefCounter (0), 
		m_LastPublishedTimestamp (0), m_ReadyChecker(service)
	{
		if (keys.IsOfflineSignature () && GetLeaseSetType () == i2p::data::NETDB_STORE_TYPE_LEASESET)
			SetLeaseSetType (i2p::data::NETDB_STORE_TYPE_STANDARD_LEASESET2); // offline keys can be published with LS2 only

		// extract encryption type params for LS2
		std::set<i2p::data::CryptoKeyType> encryptionKeyTypes;
		if (params)
		{
			auto it = params->find (I2CP_PARAM_LEASESET_ENCRYPTION_TYPE);
			if (it != params->end ())
			{
				// comma-separated values
				std::vector<std::string> values;
				boost::split(values, it->second, boost::is_any_of(","));
				for (auto& it1: values)
				{
					try
					{
						i2p::data::CryptoKeyType cryptoType = std::stoi(it1);
#if !OPENSSL_PQ
						if (cryptoType <= i2p::data::CRYPTO_KEY_TYPE_ECIES_X25519_AEAD) // skip PQ keys if not supported
#endif					
						{
							if (!m_PreferredCryptoType && cryptoType)
								m_PreferredCryptoType = cryptoType; // first non-zero in the list
							encryptionKeyTypes.insert (cryptoType);
						}	
					}
					catch (std::exception& ex)
					{
						LogPrint (eLogInfo, "Destination: Unexpected crypto type ", it1, ". ", ex.what ());
						continue;
					}
				}
			}
		}
		// if no param or valid crypto type use from identity
		if (encryptionKeyTypes.empty ())
			encryptionKeyTypes.insert ( { GetIdentity ()->GetCryptoKeyType (),
#if OPENSSL_PQ
				i2p::data::CRYPTO_KEY_TYPE_ECIES_MLKEM768_X25519_AEAD,
#endif				
				i2p::data::CRYPTO_KEY_TYPE_ECIES_X25519_AEAD }); // usually 0,4 or 0,6,4 if post quantum

		for (auto& it: encryptionKeyTypes)
		{
			auto encryptionKey = std::make_shared<i2p::crypto::LocalEncryptionKey> (it);
			if (IsPublic ())
				PersistTemporaryKeys (encryptionKey);
			else
				encryptionKey->GenerateKeys ();
			encryptionKey->CreateDecryptor ();
			if (it > i2p::data::CRYPTO_KEY_TYPE_ELGAMAL && GetLeaseSetType () == i2p::data::NETDB_STORE_TYPE_LEASESET)
				SetLeaseSetType (i2p::data::NETDB_STORE_TYPE_STANDARD_LEASESET2); // Only DSA can use LeaseSet1
			m_EncryptionKeys.emplace (it, encryptionKey);
		}

		if (IsPublic ())
			LogPrint (eLogInfo, "Destination: Local address ", GetIdentHash().ToBase32 (), " created");

		try
		{
			if (params)
			{
				// extract streaming params
				auto it = params->find (I2CP_PARAM_STREAMING_INITIAL_ACK_DELAY);
				if (it != params->end ())
					m_StreamingAckDelay = std::stoi(it->second);
				it = params->find (I2CP_PARAM_STREAMING_MAX_OUTBOUND_SPEED);
				if (it != params->end ())
					m_StreamingOutboundSpeed = std::stoi(it->second);
				it = params->find (I2CP_PARAM_STREAMING_MAX_INBOUND_SPEED);
				if (it != params->end ())
					m_StreamingInboundSpeed = std::stoi(it->second);
				it = params->find (I2CP_PARAM_STREAMING_MAX_CONCURRENT_STREAMS);
				if (it != params->end ())
					m_StreamingMaxConcurrentStreams = std::stoi(it->second);
				it = params->find (I2CP_PARAM_STREAMING_MAX_WINDOW_SIZE);
				if (it != params->end ())
				{	
					m_StreamingMaxWindowSize = std::stoi(it->second);
					if (m_StreamingMaxWindowSize < i2p::stream::MIN_WINDOW_SIZE) 
						m_StreamingMaxWindowSize = i2p::stream::MIN_WINDOW_SIZE;
				}	
				it = params->find (I2CP_PARAM_STREAMING_ANSWER_PINGS);
				if (it != params->end ())
					m_IsStreamingAnswerPings = GetBoolParamValue (it->second);
				it = params->find (I2CP_PARAM_STREAMING_DONT_SIGN);
				if (it != params->end ())
					m_IsStreamingDontSign = GetBoolParamValue (it->second);
				
				if (GetLeaseSetType () == i2p::data::NETDB_STORE_TYPE_ENCRYPTED_LEASESET2)
				{
					// authentication for encrypted LeaseSet
					auto authType = GetAuthType ();
					if (authType > 0)
					{
						m_AuthKeys = std::make_shared<std::vector<i2p::data::AuthPublicKey> >();
						if (authType == i2p::data::ENCRYPTED_LEASESET_AUTH_TYPE_DH)
							ReadAuthKey (I2CP_PARAM_LEASESET_CLIENT_DH, params);
						else if (authType == i2p::data::ENCRYPTED_LEASESET_AUTH_TYPE_PSK)
							ReadAuthKey (I2CP_PARAM_LEASESET_CLIENT_PSK, params);
						else
							LogPrint (eLogError, "Destination: Unexpected auth type: ", authType);
						if (m_AuthKeys->size ())
							LogPrint (eLogInfo, "Destination: ", m_AuthKeys->size (), " auth keys read");
						else
						{
							LogPrint (eLogCritical, "Destination: No auth keys read for auth type: ", authType);
							m_AuthKeys = nullptr;
						}
					}
				}
			}
		}
		catch (std::exception & ex)
		{
			LogPrint(eLogCritical, "Destination: Unable to parse parameters for destination: ", ex.what());
		}
	}

	ClientDestination::~ClientDestination ()
	{
	}

	void ClientDestination::Start ()
	{
		LeaseSetDestination::Start ();
		m_StreamingDestination = std::make_shared<i2p::stream::StreamingDestination> (GetSharedFromThis ()); // TODO:
		m_StreamingDestination->Start ();
		for (auto& it: m_StreamingDestinationsByPorts)
			it.second->Start ();
	}

	void ClientDestination::Stop ()
	{
		LogPrint(eLogDebug, "Destination: Stopping destination ", GetIdentHash().ToBase32(), ".b32.i2p");
		m_ReadyChecker.cancel();
		LogPrint(eLogDebug, "Destination: -> Stopping Streaming Destination");
		m_StreamingDestination->Stop ();
		//m_StreamingDestination->SetOwner (nullptr);
		m_StreamingDestination = nullptr;

		LogPrint(eLogDebug, "Destination: -> Stopping Streaming Destination by ports");
		for (auto& it: m_StreamingDestinationsByPorts)
		{
			it.second->Stop ();
			//it.second->SetOwner (nullptr);
		}
		m_StreamingDestinationsByPorts.clear ();
		m_LastStreamingDestination = nullptr;

		if (m_DatagramDestination)
		{
			LogPrint(eLogDebug, "Destination: -> Stopping Datagram Destination");
			delete m_DatagramDestination;
			m_DatagramDestination = nullptr;
		}
		LeaseSetDestination::Stop ();
		LogPrint(eLogDebug, "Destination: -> Stopping done");
	}

	void ClientDestination::HandleDataMessage (const uint8_t * buf, size_t len,
		i2p::garlic::ECIESX25519AEADRatchetSession * from)
	{
		uint32_t length = bufbe32toh (buf);
		if(length > len - 4)
		{
			LogPrint(eLogError, "Destination: Data message length ", length, " exceeds buffer length ", len);
			return;
		}
		buf += 4;
		// we assume I2CP payload
		uint16_t fromPort = bufbe16toh (buf + 4), // source
			toPort = bufbe16toh (buf + 6); // destination
		switch (buf[9])
		{
			case PROTOCOL_TYPE_STREAMING:
			{
				// streaming protocol
				if (toPort != m_LastPort || !m_LastStreamingDestination)
				{
					m_LastStreamingDestination = GetStreamingDestination (toPort);
					if (!m_LastStreamingDestination)
						m_LastStreamingDestination = m_StreamingDestination; // if no destination on port use default
					m_LastPort = toPort;
				}
				if (m_LastStreamingDestination)
					m_LastStreamingDestination->HandleDataMessagePayload (buf, length, from);
				else
					LogPrint (eLogError, "Destination: Missing streaming destination");
			}
			break;
			case PROTOCOL_TYPE_DATAGRAM:
			case PROTOCOL_TYPE_RAW:	
			case PROTOCOL_TYPE_DATAGRAM2:
			case PROTOCOL_TYPE_DATAGRAM3:	
				// datagram protocol
				if (m_DatagramDestination)
					m_DatagramDestination->HandleDataMessagePayload (fromPort, toPort, buf, length, buf[9], from);
				else
					LogPrint (eLogError, "Destination: Missing datagram destination");
			break;
			default:
				LogPrint (eLogError, "Destination: Data: Unexpected protocol ", buf[9]);
		}
	}

	void ClientDestination::CreateStream (StreamRequestComplete streamRequestComplete, const i2p::data::IdentHash& dest, uint16_t port)
	{
		if (!streamRequestComplete)
		{
			LogPrint (eLogError, "Destination: Request callback is not specified in CreateStream");
			return;
		}
		auto leaseSet = FindLeaseSet (dest);
		if (leaseSet)
		{
			auto stream = CreateStream (leaseSet, port);
			boost::asio::post (GetService (), [streamRequestComplete, stream]()
				{
					streamRequestComplete(stream);
				});
		}
		else
		{
			auto s = GetSharedFromThis ();
			RequestDestination (dest,
				[s, streamRequestComplete, port](std::shared_ptr<const i2p::data::LeaseSet> ls)
				{
					if (ls)
						streamRequestComplete(s->CreateStream (ls, port));
					else
						streamRequestComplete (nullptr);
				});
		}
	}

	void ClientDestination::CreateStream (StreamRequestComplete streamRequestComplete, std::shared_ptr<const i2p::data::BlindedPublicKey> dest, uint16_t port)
	{
		if (!streamRequestComplete)
		{
			LogPrint (eLogError, "Destination: Request callback is not specified in CreateStream");
			return;
		}
		auto s = GetSharedFromThis ();
		RequestDestinationWithEncryptedLeaseSet (dest,
			[s, streamRequestComplete, port](std::shared_ptr<i2p::data::LeaseSet> ls)
			{
				if (ls)
					streamRequestComplete(s->CreateStream (ls, port));
				else
					streamRequestComplete (nullptr);
			});
	}

	template<typename Dest>
	std::shared_ptr<i2p::stream::Stream> ClientDestination::CreateStreamSync (const Dest& dest, uint16_t port)
	{
		volatile bool done = false;
		std::shared_ptr<i2p::stream::Stream> stream;
		std::condition_variable streamRequestComplete;
		std::mutex streamRequestCompleteMutex;
		CreateStream (
			[&done, &streamRequestComplete, &streamRequestCompleteMutex, &stream](std::shared_ptr<i2p::stream::Stream> s)
		    {
				stream = s;
				std::unique_lock<std::mutex> l(streamRequestCompleteMutex);
				streamRequestComplete.notify_all ();
				done = true;
			},
		    dest, port);
		while (!done)
		{
			std::unique_lock<std::mutex> l(streamRequestCompleteMutex);
			if (!done)
				streamRequestComplete.wait (l);
		}
		return stream;
	}

	std::shared_ptr<i2p::stream::Stream> ClientDestination::CreateStream (const i2p::data::IdentHash& dest, uint16_t port)
	{
		return CreateStreamSync (dest, port);
	}

	std::shared_ptr<i2p::stream::Stream> ClientDestination::CreateStream (std::shared_ptr<const i2p::data::BlindedPublicKey> dest, uint16_t port)
	{
		return CreateStreamSync (dest, port);
	}

	std::shared_ptr<i2p::stream::Stream> ClientDestination::CreateStream (std::shared_ptr<const i2p::data::LeaseSet> remote, uint16_t port)
	{
		if (m_StreamingDestination)
			return m_StreamingDestination->CreateNewOutgoingStream (remote, port);
		else
			return nullptr;
	}

	void ClientDestination::SendPing (const i2p::data::IdentHash& to)
	{
		if (m_StreamingDestination)
		{
			auto leaseSet = FindLeaseSet (to);
			if (leaseSet)
				m_StreamingDestination->SendPing (leaseSet);
			else
			{
				auto s = m_StreamingDestination;
				RequestDestination (to,
					[s](std::shared_ptr<const i2p::data::LeaseSet> ls)
					{
						if (ls) s->SendPing (ls);
					});
			}
		}
	}

	void ClientDestination::SendPing (std::shared_ptr<const i2p::data::BlindedPublicKey> to)
	{
		auto s = m_StreamingDestination;
		RequestDestinationWithEncryptedLeaseSet (to,
			[s](std::shared_ptr<const i2p::data::LeaseSet> ls)
			{
				if (ls) s->SendPing (ls);
			});
	}

	std::shared_ptr<i2p::stream::StreamingDestination> ClientDestination::GetStreamingDestination (uint16_t port) const
	{
		if (port)
		{
			auto it = m_StreamingDestinationsByPorts.find (port);
			if (it != m_StreamingDestinationsByPorts.end ())
				return it->second;
		}
		else // if port is zero, use default destination
			return m_StreamingDestination;
		return nullptr;
	}

	void ClientDestination::AcceptStreams (const i2p::stream::StreamingDestination::Acceptor& acceptor)
	{
		if (m_StreamingDestination)
			m_StreamingDestination->SetAcceptor (acceptor);
	}

	void ClientDestination::StopAcceptingStreams ()
	{
		if (m_StreamingDestination)
			m_StreamingDestination->ResetAcceptor ();
	}

	bool ClientDestination::IsAcceptingStreams () const
	{
		if (m_StreamingDestination)
			return m_StreamingDestination->IsAcceptorSet ();
		return false;
	}

	void ClientDestination::AcceptOnce (const i2p::stream::StreamingDestination::Acceptor& acceptor)
	{
		if (m_StreamingDestination)
			m_StreamingDestination->AcceptOnce (acceptor);
	}

	std::shared_ptr<i2p::stream::StreamingDestination> ClientDestination::CreateStreamingDestination (uint16_t port, bool gzip)
	{
		auto dest = std::make_shared<i2p::stream::StreamingDestination> (GetSharedFromThis (), port, gzip);
		if (port)
			m_StreamingDestinationsByPorts[port] = dest;
		else // update default
			m_StreamingDestination = dest;
		return dest;
	}

	std::shared_ptr<i2p::stream::StreamingDestination> ClientDestination::RemoveStreamingDestination (uint16_t port)
	{
		if (port)
		{
			auto it = m_StreamingDestinationsByPorts.find (port);
			if (it != m_StreamingDestinationsByPorts.end ())
			{
				auto ret = it->second;
				m_StreamingDestinationsByPorts.erase (it);
				return ret;
			}
		}
		return nullptr;
	}

	i2p::datagram::DatagramDestination * ClientDestination::CreateDatagramDestination (bool gzip, 
		i2p::datagram::DatagramVersion version)
	{
		if (!m_DatagramDestination)
			m_DatagramDestination = new i2p::datagram::DatagramDestination (GetSharedFromThis (), gzip, version);
		return m_DatagramDestination;
	}

	std::vector<std::shared_ptr<const i2p::stream::Stream> > ClientDestination::GetAllStreams () const
	{
		std::vector<std::shared_ptr<const i2p::stream::Stream> > ret;
		if (m_StreamingDestination)
		{
			for (auto& it: m_StreamingDestination->GetStreams ())
				ret.push_back (it.second);
		}
		for (auto& it: m_StreamingDestinationsByPorts)
			for (auto& it1: it.second->GetStreams ())
				ret.push_back (it1.second);
		return ret;
	}

	void ClientDestination::PersistTemporaryKeys (std::shared_ptr<i2p::crypto::LocalEncryptionKey> keys)
	{
		if (!keys) return;
		std::string ident = GetIdentHash().ToBase32();
		std::string path  = i2p::fs::DataDirPath("destinations", ident + "." + std::to_string (keys->keyType) + ".dat");
		std::ifstream f(path, std::ifstream::binary);
		if (f) 
		{
			size_t len = 0;
			if (keys->keyType == i2p::data::CRYPTO_KEY_TYPE_ELGAMAL)
				len = 512;
			else if (keys->keyType == i2p::data::CRYPTO_KEY_TYPE_ECIES_X25519_AEAD)
			{	
				f.seekg (0, std::ios::end);
				len = f.tellg();
				f.seekg (0, std::ios::beg);
			}
				
			if (len == 512)
			{    
				char pub[256], priv[256];
				f.read (pub, 256);
				memcpy (keys->pub.data(), pub, keys->pub.size());
				f.read (priv, 256);
				memcpy (keys->priv.data (), priv, keys->priv.size ());
			}
			else
			{
				f.read ((char *)keys->pub.data(), keys->pub.size());
				f.read ((char *)keys->priv.data(), keys->priv.size());
			}	
			if (f) 
				return;
			else
				LogPrint(eLogWarning, "Destination: Can't read keys from ", path);
		}

		LogPrint (eLogInfo, "Destination: Creating new temporary keys of type ", keys->keyType, " for address ", ident, ".b32.i2p");
		memset (keys->priv.data (), 0, keys->priv.size ());
		memset (keys->pub.data (), 0, keys->pub.size ());
		keys->GenerateKeys ();
		
		std::ofstream f1 (path, std::ofstream::binary | std::ofstream::out);
		if (f1) 
		{
			f1.write ((char *)keys->pub.data (), keys->pub.size ());
			f1.write ((char *)keys->priv.data (), keys->priv.size ());
		}
		if (!f1)
			LogPrint(eLogError, "Destination: Can't save keys to ", path);
	}

	void ClientDestination::CreateNewLeaseSet (const std::vector<std::shared_ptr<i2p::tunnel::InboundTunnel> >& tunnels)
	{
		std::shared_ptr<i2p::data::LocalLeaseSet> leaseSet;
		if (GetLeaseSetType () == i2p::data::NETDB_STORE_TYPE_LEASESET)
		{
			auto it = m_EncryptionKeys.find (i2p::data::CRYPTO_KEY_TYPE_ELGAMAL);
			if (it != m_EncryptionKeys.end ())
			{
				leaseSet = std::make_shared<i2p::data::LocalLeaseSet> (GetIdentity (), it->second->pub.data (), tunnels);
				// sign
				Sign (leaseSet->GetBuffer (), leaseSet->GetBufferLen () - leaseSet->GetSignatureLen (), leaseSet->GetSignature ());
			}
			else
				LogPrint (eLogError, "Destinations: Wrong encryption key type for LeaseSet type 1");
		}
		else
		{
			// standard LS2 (type 3) first
			if (m_EncryptionKeys.empty ())
			{
				LogPrint (eLogError, "Destinations: No encryption keys");
				return;
			}	
			
			i2p::data::LocalLeaseSet2::EncryptionKeys keySections;
			std::shared_ptr<const i2p::crypto::LocalEncryptionKey> preferredSection;
			if (m_EncryptionKeys.size () == 1)
				preferredSection = m_EncryptionKeys.begin ()->second; // only key
			else
			{	
				for (const auto& it: m_EncryptionKeys)
					if (it.first == m_PreferredCryptoType)
						preferredSection = it.second;
					else
						keySections.push_back (it.second);
			}	
			if (preferredSection) 
				keySections.push_front (preferredSection); // make preferred first
			
			auto publishedTimestamp = i2p::util::GetSecondsSinceEpoch ();
			if (publishedTimestamp <= m_LastPublishedTimestamp)
			{
				LogPrint (eLogDebug, "Destination: LeaseSet update at the same second");
				publishedTimestamp++; // force newer timestamp
			}
			bool isPublishedEncrypted = GetLeaseSetType () == i2p::data::NETDB_STORE_TYPE_ENCRYPTED_LEASESET2;
			auto ls2 = std::make_shared<i2p::data::LocalLeaseSet2> (i2p::data::NETDB_STORE_TYPE_STANDARD_LEASESET2,
				m_Keys, keySections, tunnels, IsPublic (), publishedTimestamp, isPublishedEncrypted);
			if (isPublishedEncrypted) // encrypt if type 5
				ls2 = std::make_shared<i2p::data::LocalEncryptedLeaseSet2> (ls2, m_Keys, GetAuthType (), m_AuthKeys);
			leaseSet = ls2;
			m_LastPublishedTimestamp = publishedTimestamp;
		}
		SetLeaseSet (leaseSet);
	}

	void ClientDestination::CleanupDestination ()
	{
		if (m_DatagramDestination) m_DatagramDestination->CleanUp ();
	}

	bool ClientDestination::Decrypt (const uint8_t * encrypted, uint8_t * data, i2p::data::CryptoKeyType preferredCrypto) const
	{
		std::shared_ptr<i2p::crypto::LocalEncryptionKey> encryptionKey;
		if (!m_EncryptionKeys.empty ())
		{
			if (m_EncryptionKeys.rbegin ()->first == preferredCrypto)
				encryptionKey = m_EncryptionKeys.rbegin ()->second;
			else
			{
				auto it = m_EncryptionKeys.find (preferredCrypto);
				if (it != m_EncryptionKeys.end ())
					encryptionKey = it->second;
			}	
			if (!encryptionKey)
				encryptionKey = m_EncryptionKeys.rbegin ()->second;
		}	
		if (encryptionKey)
			return encryptionKey->decryptor->Decrypt (encrypted, data);
		else
			LogPrint (eLogError, "Destinations: Decryptor is not set");
		return false;
	}

	bool ClientDestination::SupportsEncryptionType (i2p::data::CryptoKeyType keyType) const
	{
#if __cplusplus >= 202002L // C++20
		return m_EncryptionKeys.contains (keyType);
#else		
		return m_EncryptionKeys.count (keyType) > 0;
#endif		
	}

	i2p::data::CryptoKeyType ClientDestination::GetRatchetsHighestCryptoType () const
	{
		if (m_EncryptionKeys.empty ()) return 0;
		auto cryptoType = m_EncryptionKeys.rbegin ()->first; 
		return cryptoType >= i2p::data::CRYPTO_KEY_TYPE_ECIES_X25519_AEAD ? cryptoType : 0;
	}
		
	const uint8_t * ClientDestination::GetEncryptionPublicKey (i2p::data::CryptoKeyType keyType) const
	{
		auto it = m_EncryptionKeys.find (keyType);
		if (it != m_EncryptionKeys.end ())
			return it->second->pub.data ();
		return nullptr;
	}

	void ClientDestination::ReadAuthKey (const std::string& group, const std::map<std::string, std::string> * params)
	{
		for (auto it: *params)
		if (it.first.length () >= group.length () && !it.first.compare (0, group.length (), group))
		{
			auto pos = it.second.find (':');
			if (pos != std::string::npos)
			{
				i2p::data::AuthPublicKey pubKey;
				if (pubKey.FromBase64 (it.second.substr (pos+1)))
					m_AuthKeys->push_back (pubKey);
				else
					LogPrint (eLogCritical, "Destination: Unexpected auth key: ", it.second.substr (pos+1));
			}
		}
	}

	bool ClientDestination::DeleteStream (uint32_t recvStreamID)
	{
		if (m_StreamingDestination->DeleteStream (recvStreamID))
			return true;
		for (auto it: m_StreamingDestinationsByPorts)
			if (it.second->DeleteStream (recvStreamID))
				return true;
		return false;
	}

	RunnableClientDestination::RunnableClientDestination (const i2p::data::PrivateKeys& keys, bool isPublic, const std::map<std::string, std::string> * params):
		RunnableService ("Destination"),
		ClientDestination (GetIOService (), keys, isPublic, params)
	{
		if (!GetNickname ().empty ())
			RunnableService::SetName (GetNickname ());
	}

	RunnableClientDestination::~RunnableClientDestination ()
	{
		if (IsRunning ())
			Stop ();
	}

	void RunnableClientDestination::Start ()
	{
		if (!IsRunning ())
		{
			ClientDestination::Start ();
			StartIOService ();
		}
	}

	void RunnableClientDestination::Stop ()
	{
		if (IsRunning ())
		{
			ClientDestination::Stop ();
			StopIOService ();
		}
	}

}
}