File: NTCP2.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 (2033 lines) | stat: -rw-r--r-- 68,862 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
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
/*
* 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 <openssl/rand.h>
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <stdlib.h>
#include <vector>
#include "Log.h"
#include "I2PEndian.h"
#include "Crypto.h"
#include "Siphash.h"
#include "RouterContext.h"
#include "Transports.h"
#include "NetDb.hpp"
#include "HTTP.h"
#include "util.h"
#include "Socks5.h"
#include "NTCP2.h"

#if defined(__linux__) && !defined(_NETINET_IN_H)
	#include <linux/in6.h>
#endif

namespace i2p
{
namespace transport
{
	NTCP2Establisher::NTCP2Establisher ():
		m_SessionConfirmedBuffer (nullptr)
	{
	}

	NTCP2Establisher::~NTCP2Establisher ()
	{
		delete[] m_SessionConfirmedBuffer;
	}

	bool NTCP2Establisher::KeyDerivationFunction1 (const uint8_t * pub, i2p::crypto::X25519Keys& priv, const uint8_t * rs, const uint8_t * epub)
	{
		i2p::crypto::InitNoiseXKState (*this, rs);
		// h = SHA256(h || epub)
		MixHash (epub, 32);
		// x25519 between pub and priv
		uint8_t inputKeyMaterial[32];
		if (!priv.Agree (pub, inputKeyMaterial)) return false;
		MixKey (inputKeyMaterial);
		return true;
	}

	bool NTCP2Establisher::KDF1Alice ()
	{
		return KeyDerivationFunction1 (m_RemoteStaticKey, *m_EphemeralKeys, m_RemoteStaticKey, GetPub ());
	}

	bool NTCP2Establisher::KDF1Bob ()
	{
		return KeyDerivationFunction1 (GetRemotePub (), i2p::context.GetNTCP2StaticKeys (), i2p::context.GetNTCP2StaticPublicKey (), GetRemotePub ());
	}

	bool NTCP2Establisher::KeyDerivationFunction2 (const uint8_t * sessionRequest, size_t sessionRequestLen, const uint8_t * epub)
	{
		MixHash (sessionRequest + 32, 32); // encrypted payload

		int paddingLength = sessionRequestLen - 64;
		if (paddingLength > 0)
			MixHash (sessionRequest + 64, paddingLength);
		MixHash (epub, 32);

		// x25519 between remote pub and ephemaral priv
		uint8_t inputKeyMaterial[32];
		if (!m_EphemeralKeys->Agree (GetRemotePub (), inputKeyMaterial)) return false;
		MixKey (inputKeyMaterial);
		return true;
	}

	bool NTCP2Establisher::KDF2Alice ()
	{
		return KeyDerivationFunction2 (m_SessionRequestBuffer, m_SessionRequestBufferLen, GetRemotePub ());
	}

	bool NTCP2Establisher::KDF2Bob ()
	{
		return KeyDerivationFunction2 (m_SessionRequestBuffer, m_SessionRequestBufferLen, GetPub ());
	}

	bool NTCP2Establisher::KDF3Alice ()
	{
		uint8_t inputKeyMaterial[32];
		if (!i2p::context.GetNTCP2StaticKeys ().Agree (GetRemotePub (), inputKeyMaterial)) return false;
		MixKey (inputKeyMaterial);
		return true;
	}

	bool NTCP2Establisher::KDF3Bob ()
	{
		uint8_t inputKeyMaterial[32];
		if (!m_EphemeralKeys->Agree (m_RemoteStaticKey, inputKeyMaterial)) return false;
		MixKey (inputKeyMaterial);
		return true;
	}

	void NTCP2Establisher::CreateEphemeralKey ()
	{
		m_EphemeralKeys = i2p::transport::transports.GetNextX25519KeysPair ();
	}

	bool NTCP2Establisher::CreateSessionRequestMessage (std::mt19937& rng)
	{
		// create buffer and fill padding
		auto paddingLength = rng () % (NTCP2_SESSION_REQUEST_MAX_SIZE - 64); // message length doesn't exceed 287 bytes
		m_SessionRequestBufferLen = paddingLength + 64;
		RAND_bytes (m_SessionRequestBuffer + 64, paddingLength);
		// encrypt X
		i2p::crypto::CBCEncryption encryption;
		encryption.SetKey (m_RemoteIdentHash);
		encryption.Encrypt (GetPub (), 32, m_IV, m_SessionRequestBuffer); // X
		memcpy (m_IV, m_SessionRequestBuffer + 16, 16); // save last block as IV for SessionCreated
		// encryption key for next block
		if (!KDF1Alice ()) return false;
		// fill options
		uint8_t options[32]; // actual options size is 16 bytes
		memset (options, 0, 16);
		options[0] = i2p::context.GetNetID (); // network ID
		options[1] = 2; // ver
		htobe16buf (options + 2, paddingLength); // padLen
		// m3p2Len
		auto riBuffer = i2p::context.CopyRouterInfoBuffer ();
		auto bufLen = riBuffer->GetBufferLen ();
		m3p2Len = bufLen + 4 + 16; // (RI header + RI + MAC for now) TODO: implement options
		htobe16buf (options + 4, m3p2Len);
		// fill m3p2 payload (RouterInfo block)
		m_SessionConfirmedBuffer = new uint8_t[m3p2Len + 48]; // m3p1 is 48 bytes
		uint8_t * m3p2 = m_SessionConfirmedBuffer + 48;
		m3p2[0] = eNTCP2BlkRouterInfo; // block
		htobe16buf (m3p2 + 1, bufLen + 1); // flag + RI
		m3p2[3] = 0; // flag
		memcpy (m3p2 + 4, riBuffer->data (), bufLen); // TODO: eliminate extra copy
		// 2 bytes reserved
		htobe32buf (options + 8, (i2p::util::GetMillisecondsSinceEpoch () + 500)/1000); // tsA, rounded to seconds
		// 4 bytes reserved
		// encrypt options
		if (!Encrypt (options, m_SessionRequestBuffer + 32, 16))
		{
			LogPrint (eLogWarning, "NTCP2: SessionRequest failed to encrypt options");
			return false;
		}	
		return true;
	}

	bool NTCP2Establisher::CreateSessionCreatedMessage (std::mt19937& rng)
	{
		auto paddingLen = rng () % (NTCP2_SESSION_CREATED_MAX_SIZE - 64);
		m_SessionCreatedBufferLen = paddingLen + 64;
		RAND_bytes (m_SessionCreatedBuffer + 64, paddingLen);
		// encrypt Y
		i2p::crypto::CBCEncryption encryption;
		encryption.SetKey (i2p::context.GetIdentHash ());
		encryption.Encrypt (GetPub (), 32, m_IV, m_SessionCreatedBuffer); // Y
		// encryption key for next block (m_K)
		if (!KDF2Bob ()) return false;
		uint8_t options[16];
		memset (options, 0, 16);
		htobe16buf (options + 2, paddingLen); // padLen
		htobe32buf (options + 8, (i2p::util::GetMillisecondsSinceEpoch () + 500)/1000); // tsB, rounded to seconds
		// encrypt options
		if (!Encrypt (options, m_SessionCreatedBuffer + 32, 16))
		{
			LogPrint (eLogWarning, "NTCP2: SessionCreated failed to encrypt options");
			return false;
		}	
		return true;
	}

	bool NTCP2Establisher::CreateSessionConfirmedMessagePart1 ()
	{
		// update AD
		MixHash (m_SessionCreatedBuffer + 32, 32);	// encrypted payload
		int paddingLength = m_SessionCreatedBufferLen - 64;
		if (paddingLength > 0)
			MixHash (m_SessionCreatedBuffer + 64, paddingLength);

		// part1 48 bytes, n = 1
		if (!Encrypt (i2p::context.GetNTCP2StaticPublicKey (), m_SessionConfirmedBuffer, 32))
		{
			LogPrint (eLogWarning, "NTCP2: SessionConfirmed failed to encrypt part1");
			return false;
		}	
		return true;		
	}

	bool NTCP2Establisher::CreateSessionConfirmedMessagePart2 ()
	{
		// part 2
		// update AD again
		MixHash (m_SessionConfirmedBuffer, 48);
		// encrypt m3p2, it must be filled in SessionRequest
		if (!KDF3Alice ()) return false; // MixKey, n = 0
		uint8_t * m3p2 = m_SessionConfirmedBuffer + 48;
		if (!Encrypt (m3p2, m3p2, m3p2Len - 16))
		{
			LogPrint (eLogWarning, "NTCP2: SessionConfirmed failed to encrypt part2");
			return false;
		}	
		// update h again
		MixHash (m3p2, m3p2Len); //h = SHA256(h || ciphertext)
		return true;
	}

	bool NTCP2Establisher::ProcessSessionRequestMessage (uint16_t& paddingLen, bool& clockSkew)
	{
		clockSkew = false;
		// decrypt X
		i2p::crypto::CBCDecryption decryption;
		decryption.SetKey (i2p::context.GetIdentHash ());
		decryption.Decrypt (m_SessionRequestBuffer, 32, i2p::context.GetNTCP2IV (), GetRemotePub ());
		memcpy (m_IV, m_SessionRequestBuffer + 16, 16); // save last block as IV for SessionCreated
		// decryption key for next block
		if (!KDF1Bob ())
		{
			LogPrint (eLogWarning, "NTCP2: SessionRequest KDF failed");
			return false;
		}	
		// verify MAC and decrypt options block (32 bytes)
		uint8_t options[16];
		if (Decrypt (m_SessionRequestBuffer + 32, options, 16)) 
		{
			// options
			if (options[0] && options[0] != i2p::context.GetNetID ())
			{
				LogPrint (eLogWarning, "NTCP2: SessionRequest networkID ", (int)options[0], " mismatch. Expected ", i2p::context.GetNetID ());
				return false;
			}
			if (options[1] == 2) // ver is always 2
			{
				paddingLen = bufbe16toh (options + 2);
				m_SessionRequestBufferLen = paddingLen + 64;
				m3p2Len = bufbe16toh (options + 4);
				if (m3p2Len < 16)
				{
					LogPrint (eLogWarning, "NTCP2: SessionRequest m3p2len=", m3p2Len, " is too short");
					return false;
				}
				// check timestamp
				auto ts = i2p::util::GetSecondsSinceEpoch ();
				uint32_t tsA = bufbe32toh (options + 8);
				if (tsA < ts - NTCP2_CLOCK_SKEW || tsA > ts + NTCP2_CLOCK_SKEW)
				{
					LogPrint (eLogWarning, "NTCP2: SessionRequest time difference ", (int)(ts - tsA), " exceeds clock skew");
					clockSkew = true;
					// we send SessionCreate to let Alice know our time and then close session
				}
			}
			else
			{
				LogPrint (eLogWarning, "NTCP2: SessionRequest version mismatch ", (int)options[1]);
				return false;
			}
		}
		else
		{
			LogPrint (eLogWarning, "NTCP2: SessionRequest AEAD verification failed ");
			return false;
		}
		return true;
	}

	bool NTCP2Establisher::ProcessSessionCreatedMessage (uint16_t& paddingLen)
	{
		m_SessionCreatedBufferLen = 64;
		// decrypt Y
		i2p::crypto::CBCDecryption decryption;
		decryption.SetKey (m_RemoteIdentHash);
		decryption.Decrypt (m_SessionCreatedBuffer, 32, m_IV, GetRemotePub ());
		// decryption key for next block (m_K)
		if (!KDF2Alice ())
		{
			LogPrint (eLogWarning, "NTCP2: SessionCreated KDF failed");
			return false;
		}	
		// decrypt and verify MAC
		uint8_t payload[16];
		if (Decrypt (m_SessionCreatedBuffer + 32, payload, 16)) 
		{
			// options
			paddingLen = bufbe16toh(payload + 2);
			// check timestamp
			auto ts = i2p::util::GetSecondsSinceEpoch ();
			uint32_t tsB = bufbe32toh (payload + 8);
			if (tsB < ts - NTCP2_CLOCK_SKEW || tsB > ts + NTCP2_CLOCK_SKEW)
			{
				LogPrint (eLogWarning, "NTCP2: SessionCreated time difference ", (int)(ts - tsB), " exceeds clock skew");
				return false;
			}
		}
		else
		{
			LogPrint (eLogWarning, "NTCP2: SessionCreated AEAD verification failed ");
			return false;
		}
		return true;
	}

	bool NTCP2Establisher::ProcessSessionConfirmedMessagePart1 ()
	{
		// update AD
		MixHash (m_SessionCreatedBuffer + 32, 32);	// encrypted payload
		int paddingLength = m_SessionCreatedBufferLen - 64;
		if (paddingLength > 0)
			MixHash (m_SessionCreatedBuffer + 64, paddingLength);

		// decrypt S, n = 1
		if (!Decrypt (m_SessionConfirmedBuffer, m_RemoteStaticKey, 32))
		{
			LogPrint (eLogWarning, "NTCP2: SessionConfirmed Part1 AEAD verification failed ");
			return false;
		}
		return true;
	}

	bool NTCP2Establisher::ProcessSessionConfirmedMessagePart2 (uint8_t * m3p2Buf)
	{
		// update AD again
		MixHash (m_SessionConfirmedBuffer, 48);

		if (!KDF3Bob ()) // MixKey, n = 0
		{
			LogPrint (eLogWarning, "NTCP2: SessionConfirmed Part2 KDF failed");
			return false;
		}	
		if (Decrypt (m_SessionConfirmedBuffer + 48, m3p2Buf, m3p2Len - 16))
			// calculate new h again for KDF data
			MixHash (m_SessionConfirmedBuffer + 48, m3p2Len); // h = SHA256(h || ciphertext)
		else
		{
			LogPrint (eLogWarning, "NTCP2: SessionConfirmed Part2 AEAD verification failed ");
			return false;
		}
		return true;
	}

	NTCP2Session::NTCP2Session (NTCP2Server& server, std::shared_ptr<const i2p::data::RouterInfo> in_RemoteRouter,
		std::shared_ptr<const i2p::data::RouterInfo::Address> addr):
		TransportSession (in_RemoteRouter, NTCP2_ESTABLISH_TIMEOUT),
		m_Server (server), m_Socket (m_Server.GetService ()),
		m_IsEstablished (false), m_IsTerminated (false),
		m_Establisher (new NTCP2Establisher),
		m_SendKey (nullptr), m_ReceiveKey (nullptr),
#if OPENSSL_SIPHASH
		m_SendMDCtx(nullptr), m_ReceiveMDCtx (nullptr),
#else
		m_SendSipKey (nullptr), m_ReceiveSipKey (nullptr),
#endif
		m_NextReceivedLen (0), m_NextReceivedBuffer (nullptr), m_NextSendBuffer (nullptr),
		m_NextReceivedBufferSize (0), m_ReceiveSequenceNumber (0), m_SendSequenceNumber (0),
		m_IsSending (false), m_IsReceiving (false), m_NextPaddingSize (16)
	{
		if (in_RemoteRouter) // Alice
		{
			m_Establisher->m_RemoteIdentHash = GetRemoteIdentity ()->GetIdentHash ();
			if (addr)
			{
				memcpy (m_Establisher->m_RemoteStaticKey, addr->s, 32);
				memcpy (m_Establisher->m_IV, addr->i, 16);
				m_RemoteEndpoint = boost::asio::ip::tcp::endpoint (addr->host, addr->port);
			}
			else
				LogPrint (eLogWarning, "NTCP2: Missing NTCP2 address");
		}
		m_NextRouterInfoResendTime = i2p::util::GetSecondsSinceEpoch () + NTCP2_ROUTERINFO_RESEND_INTERVAL +
			m_Server.GetRng ()() % NTCP2_ROUTERINFO_RESEND_INTERVAL_THRESHOLD;
	}

	NTCP2Session::~NTCP2Session ()
	{
		delete[] m_NextReceivedBuffer;
		delete[] m_NextSendBuffer;
#if OPENSSL_SIPHASH
		if (m_SendMDCtx) EVP_MD_CTX_destroy (m_SendMDCtx);
		if (m_ReceiveMDCtx) EVP_MD_CTX_destroy (m_ReceiveMDCtx);
#endif
	}

	void NTCP2Session::Terminate ()
	{
		if (!m_IsTerminated)
		{
			m_IsTerminated = true;
			m_IsEstablished = false;
			boost::system::error_code ec;
			m_Socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
			if (ec)
				LogPrint (eLogDebug, "NTCP2: Couldn't shutdown socket: ", ec.message ());
			m_Socket.close ();
			transports.PeerDisconnected (shared_from_this ());
			m_Server.RemoveNTCP2Session (shared_from_this ());
			if (!m_IntermediateQueue.empty ())
				m_SendQueue.splice (m_SendQueue.end (), m_IntermediateQueue);
			for (auto& it: m_SendQueue)
				it->Drop ();
			m_SendQueue.clear ();
			SetSendQueueSize (0);
			auto remoteIdentity = GetRemoteIdentity ();
			if (remoteIdentity)
			{
				LogPrint (eLogDebug, "NTCP2: Session with ", GetRemoteEndpoint (),
					" (", i2p::data::GetIdentHashAbbreviation (remoteIdentity->GetIdentHash ()), ") terminated");
			}
			else
			{
				LogPrint (eLogDebug, "NTCP2: Session with ", GetRemoteEndpoint (), " terminated");
			}
		}
	}

	void NTCP2Session::Close ()
	{
		m_Socket.close ();
	}

	void NTCP2Session::TerminateByTimeout ()
	{
		SendTerminationAndTerminate (eNTCP2IdleTimeout);
	}

	void NTCP2Session::Done ()
	{
		boost::asio::post (m_Server.GetService (), std::bind (&NTCP2Session::Terminate, shared_from_this ()));
	}

	void NTCP2Session::Established ()
	{
		m_IsEstablished = true;
		m_Establisher.reset (nullptr);
		SetTerminationTimeout (NTCP2_TERMINATION_TIMEOUT + m_Server.GetRng ()() % NTCP2_TERMINATION_TIMEOUT_VARIANCE);
		SendQueue ();
		transports.PeerConnected (shared_from_this ());
	}

	void NTCP2Session::CreateNonce (uint64_t seqn, uint8_t * nonce)
	{
		memset (nonce, 0, 4);
		htole64buf (nonce + 4, seqn);
	}

	void NTCP2Session::CreateNextReceivedBuffer (size_t size)
	{
		if (m_NextReceivedBuffer)
		{
			if (size <= m_NextReceivedBufferSize)
				return; // buffer is good, do nothing
			else
				delete[] m_NextReceivedBuffer;
		}
		m_NextReceivedBuffer = new uint8_t[size];
		m_NextReceivedBufferSize = size;
	}

	void NTCP2Session::DeleteNextReceiveBuffer (uint64_t ts)
	{
		if (m_NextReceivedBuffer && !m_IsReceiving &&
			ts > GetLastActivityTimestamp () + NTCP2_RECEIVE_BUFFER_DELETION_TIMEOUT)
		{
			delete[] m_NextReceivedBuffer;
			m_NextReceivedBuffer = nullptr;
			m_NextReceivedBufferSize = 0;
		}
	}

	void NTCP2Session::KeyDerivationFunctionDataPhase ()
	{
		uint8_t k[64];
		i2p::crypto::HKDF (m_Establisher->GetCK (), nullptr, 0, "", k); // k_ab, k_ba = HKDF(ck, zerolen)
		memcpy (m_Kab, k, 32); memcpy (m_Kba, k + 32, 32);
		uint8_t master[32];
		i2p::crypto::HKDF (m_Establisher->GetCK (), nullptr, 0, "ask", master, 32); // ask_master = HKDF(ck, zerolen, info="ask")
		uint8_t h[39];
		memcpy (h, m_Establisher->GetH (), 32);
		memcpy (h + 32, "siphash", 7);
		i2p::crypto::HKDF (master, h, 39, "", master, 32); // sip_master = HKDF(ask_master, h || "siphash")
		i2p::crypto::HKDF (master, nullptr, 0, "", k); // sipkeys_ab, sipkeys_ba = HKDF(sip_master, zerolen)
		memcpy (m_Sipkeysab, k, 32); memcpy (m_Sipkeysba, k + 32, 32);
	}


	void NTCP2Session::SendSessionRequest ()
	{
		if (!m_Establisher->CreateSessionRequestMessage (m_Server.GetRng ()))
		{
			LogPrint (eLogWarning, "NTCP2: Send SessionRequest KDF failed");
			boost::asio::post (m_Server.GetService (), std::bind (&NTCP2Session::Terminate, shared_from_this ()));
			return;
		}	
		// send message
		m_HandshakeInterval = i2p::util::GetMillisecondsSinceEpoch ();
		boost::asio::async_write (m_Socket, boost::asio::buffer (m_Establisher->m_SessionRequestBuffer, m_Establisher->m_SessionRequestBufferLen), boost::asio::transfer_all (),
			std::bind(&NTCP2Session::HandleSessionRequestSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
	}

	void NTCP2Session::HandleSessionRequestSent (const boost::system::error_code& ecode, std::size_t bytes_transferred)
	{
		(void) bytes_transferred;
		if (ecode)
		{
			LogPrint (eLogWarning, "NTCP2: Couldn't send SessionRequest message: ", ecode.message ());
			Terminate ();
		}
		else
		{
			// we receive first 64 bytes (32 Y, and 32 ChaCha/Poly frame) first
			boost::asio::async_read (m_Socket, boost::asio::buffer(m_Establisher->m_SessionCreatedBuffer, 64), boost::asio::transfer_all (),
				std::bind(&NTCP2Session::HandleSessionCreatedReceived, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
		}
	}

	void NTCP2Session::HandleSessionRequestReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
	{
		if (ecode)
		{
			LogPrint (eLogWarning, "NTCP2: SessionRequest read error: ", ecode.message ());
			Terminate ();
		}
		else
		{
			m_Establisher->CreateEphemeralKey ();
			boost::asio::post (m_Server.GetEstablisherService (), 
				[s = shared_from_this (), bytes_transferred] ()
				{
					s->ProcessSessionRequest (bytes_transferred);;
				});	
		}
	}

	void NTCP2Session::ProcessSessionRequest (size_t len)
	{
		LogPrint (eLogDebug, "NTCP2: SessionRequest received ", len);
		uint16_t paddingLen = 0;
		bool clockSkew = false;
		if (m_Establisher->ProcessSessionRequestMessage (paddingLen, clockSkew))
		{
			if (clockSkew)
			{
				// we don't care about padding, send SessionCreated and close session
				SendSessionCreated ();
				boost::asio::post (m_Server.GetService (), std::bind (&NTCP2Session::Terminate, shared_from_this ()));
			}
			else if (paddingLen > 0)
			{
				if (paddingLen <= NTCP2_SESSION_REQUEST_MAX_SIZE - 64) // session request is 287 bytes max
				{
					boost::asio::async_read (m_Socket, boost::asio::buffer(m_Establisher->m_SessionRequestBuffer + 64, paddingLen), boost::asio::transfer_all (),
						std::bind(&NTCP2Session::HandleSessionRequestPaddingReceived, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
				}
				else
				{
					LogPrint (eLogWarning, "NTCP2: SessionRequest padding length ", (int)paddingLen, " is too long");
					boost::asio::post (m_Server.GetService (), std::bind (&NTCP2Session::Terminate, shared_from_this ()));
				}
			}
			else
				SendSessionCreated ();
		}
		else
			ReadSomethingAndTerminate (); // probing resistance
	}	
		
	void NTCP2Session::HandleSessionRequestPaddingReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
	{
		if (ecode)
		{
			LogPrint (eLogWarning, "NTCP2: SessionRequest padding read error: ", ecode.message ());
			Terminate ();
		}
		else
		{
			boost::asio::post (m_Server.GetEstablisherService (), 
				[s = shared_from_this ()] ()
				{
					s->SendSessionCreated ();
				});	
		}	
	}

	void NTCP2Session::SendSessionCreated ()
	{
		if (!m_Establisher->CreateSessionCreatedMessage (m_Server.GetRng ()))
		{
			LogPrint (eLogWarning, "NTCP2: Send SessionCreated KDF failed");
			boost::asio::post (m_Server.GetService (), std::bind (&NTCP2Session::Terminate, shared_from_this ()));
			return;
		}	
		// send message
		m_HandshakeInterval = i2p::util::GetMillisecondsSinceEpoch ();
		boost::asio::async_write (m_Socket, boost::asio::buffer (m_Establisher->m_SessionCreatedBuffer, m_Establisher->m_SessionCreatedBufferLen), boost::asio::transfer_all (),
			std::bind(&NTCP2Session::HandleSessionCreatedSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
	}

	void NTCP2Session::HandleSessionCreatedReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
	{
		if (ecode)
		{
			LogPrint (eLogWarning, "NTCP2: SessionCreated read error: ", ecode.message ());
			Terminate ();
		}
		else
		{
			m_HandshakeInterval = i2p::util::GetMillisecondsSinceEpoch () - m_HandshakeInterval;
			boost::asio::post (m_Server.GetEstablisherService (), 
				[s = shared_from_this (), bytes_transferred] ()
				{
					s->ProcessSessionCreated (bytes_transferred);
				});	
		}
	}

	void NTCP2Session::ProcessSessionCreated (size_t len)
	{
		LogPrint (eLogDebug, "NTCP2: SessionCreated received ", len);
		uint16_t paddingLen = 0;
		if (m_Establisher->ProcessSessionCreatedMessage (paddingLen))
		{
			if (paddingLen > 0)
			{
				if (paddingLen <= NTCP2_SESSION_CREATED_MAX_SIZE - 64) // session created is 287 bytes max
				{
					boost::asio::async_read (m_Socket, boost::asio::buffer(m_Establisher->m_SessionCreatedBuffer + 64, paddingLen), boost::asio::transfer_all (),
						std::bind(&NTCP2Session::HandleSessionCreatedPaddingReceived, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
				}
				else
				{
					LogPrint (eLogWarning, "NTCP2: SessionCreated padding length ", (int)paddingLen, " is too long");
					boost::asio::post (m_Server.GetService (), std::bind (&NTCP2Session::Terminate, shared_from_this ()));
				}
			}
			else
				SendSessionConfirmed ();
		}
		else
		{
			if (GetRemoteIdentity ())
				i2p::data::netdb.SetUnreachable (GetRemoteIdentity ()->GetIdentHash (), true);  // assume wrong s key
			boost::asio::post (m_Server.GetService (), std::bind (&NTCP2Session::Terminate, shared_from_this ()));
		}	
	}	
		
	void NTCP2Session::HandleSessionCreatedPaddingReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
	{
		if (ecode)
		{
			LogPrint (eLogWarning, "NTCP2: SessionCreated padding read error: ", ecode.message ());
			Terminate ();
		}
		else
		{
			m_Establisher->m_SessionCreatedBufferLen += bytes_transferred;
			boost::asio::post (m_Server.GetEstablisherService (), 
				[s = shared_from_this ()] ()
				{
					s->SendSessionConfirmed ();
				});	
		}
	}

	void NTCP2Session::SendSessionConfirmed ()
	{
		if (!m_Establisher->CreateSessionConfirmedMessagePart1 ()) 
		{
			boost::asio::post (m_Server.GetService (), std::bind (&NTCP2Session::Terminate, shared_from_this ()));
			return;
		}	
		if (!m_Establisher->CreateSessionConfirmedMessagePart2 ())
		{
			LogPrint (eLogWarning, "NTCP2: Send SessionConfirmed Part2 KDF failed");
			boost::asio::post (m_Server.GetService (), std::bind (&NTCP2Session::Terminate, shared_from_this ()));
			return;
		}	
		// send message
		boost::asio::async_write (m_Socket, boost::asio::buffer (m_Establisher->m_SessionConfirmedBuffer, m_Establisher->m3p2Len + 48), boost::asio::transfer_all (),
			std::bind(&NTCP2Session::HandleSessionConfirmedSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
	}

	void NTCP2Session::HandleSessionConfirmedSent (const boost::system::error_code& ecode, std::size_t bytes_transferred)
	{
		(void) bytes_transferred;
		if (ecode)
		{
			LogPrint (eLogWarning, "NTCP2: Couldn't send SessionConfirmed message: ", ecode.message ());
			Terminate ();
		}
		else
		{
			LogPrint (eLogDebug, "NTCP2: SessionConfirmed sent");
			KeyDerivationFunctionDataPhase ();
			// Alice data phase keys
			m_SendKey = m_Kab;
			m_ReceiveKey = m_Kba;
			SetSipKeys (m_Sipkeysab, m_Sipkeysba);
			memcpy (m_ReceiveIV.buf, m_Sipkeysba + 16, 8);
			memcpy (m_SendIV.buf, m_Sipkeysab + 16, 8);
			Established ();
			ReceiveLength ();

			// TODO: remove
			// m_SendQueue.push_back (CreateDeliveryStatusMsg (1));
			// SendQueue ();
		}
	}

	void NTCP2Session::HandleSessionCreatedSent (const boost::system::error_code& ecode, std::size_t bytes_transferred)
	{
		(void) bytes_transferred;
		if (ecode)
		{
			LogPrint (eLogWarning, "NTCP2: Couldn't send SessionCreated message: ", ecode.message ());
			Terminate ();
		}
		else
		{
			LogPrint (eLogDebug, "NTCP2: SessionCreated sent");
			m_Establisher->m_SessionConfirmedBuffer = new uint8_t[m_Establisher->m3p2Len + 48];
			boost::asio::async_read (m_Socket, boost::asio::buffer(m_Establisher->m_SessionConfirmedBuffer, m_Establisher->m3p2Len + 48), boost::asio::transfer_all (),
				std::bind(&NTCP2Session::HandleSessionConfirmedReceived , shared_from_this (), std::placeholders::_1, std::placeholders::_2));
		}
	}

	void NTCP2Session::HandleSessionConfirmedReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
	{
		(void) bytes_transferred;
		if (ecode)
		{
			LogPrint (eLogWarning, "NTCP2: SessionConfirmed read error: ", ecode.message ());
			Terminate ();
		}
		else
		{
			m_HandshakeInterval = i2p::util::GetMillisecondsSinceEpoch () - m_HandshakeInterval;
			boost::asio::post (m_Server.GetEstablisherService (), 
				[s = shared_from_this ()] ()
				{
					s->ProcessSessionConfirmed ();;
				});	
		}
	}

	void NTCP2Session::ProcessSessionConfirmed ()
	{
		// run on establisher thread
		LogPrint (eLogDebug, "NTCP2: SessionConfirmed received");
		// part 1
		if (m_Establisher->ProcessSessionConfirmedMessagePart1 ())
		{
			// part 2
			auto buf = std::make_shared<std::vector<uint8_t> > (m_Establisher->m3p2Len - 16); // -MAC
			if (m_Establisher->ProcessSessionConfirmedMessagePart2 (buf->data ())) // TODO:handle in establisher thread
			{
				// payload 
				// RI block must be first 
				if ((*buf)[0] != eNTCP2BlkRouterInfo)
				{
					LogPrint (eLogWarning, "NTCP2: Unexpected block ", (int)(*buf)[0], " in SessionConfirmed");
					boost::asio::post (m_Server.GetService (), std::bind (&NTCP2Session::Terminate, shared_from_this ()));
					return;
				}
				auto size = bufbe16toh (buf->data () + 1);
				if (size > buf->size () - 3 || size > i2p::data::MAX_RI_BUFFER_SIZE + 1)
				{
					LogPrint (eLogError, "NTCP2: Unexpected RouterInfo size ", size, " in SessionConfirmed");
					boost::asio::post (m_Server.GetService (), std::bind (&NTCP2Session::Terminate, shared_from_this ()));
					return;
				}
				boost::asio::post (m_Server.GetService (), 
					[s = shared_from_this (), buf, size] ()
					{
						s->EstablishSessionAfterSessionConfirmed (buf, size);
					});
			}
			else
				boost::asio::post (m_Server.GetService (), std::bind (&NTCP2Session::Terminate, shared_from_this ()));
		}
		else
			boost::asio::post (m_Server.GetService (), std::bind (&NTCP2Session::Terminate, shared_from_this ()));	
	}	

	void NTCP2Session::EstablishSessionAfterSessionConfirmed (std::shared_ptr<std::vector<uint8_t> > buf, size_t size)
	{
		// run on main NTCP2 thread
		KeyDerivationFunctionDataPhase ();
		// Bob data phase keys
		m_SendKey = m_Kba;
		m_ReceiveKey = m_Kab;
		SetSipKeys (m_Sipkeysba, m_Sipkeysab);
		memcpy (m_ReceiveIV.buf, m_Sipkeysab + 16, 8);
		memcpy (m_SendIV.buf, m_Sipkeysba + 16, 8);
		// we need to set keys for SendTerminationAndTerminate
		// TODO: check flag
		i2p::data::RouterInfo ri (buf->data () + 4, size - 1); // 1 byte block type + 2 bytes size + 1 byte flag
		if (ri.IsUnreachable ())
		{
			LogPrint (eLogError, "NTCP2: RouterInfo verification failed in SessionConfirmed from ", GetRemoteEndpoint ());
			SendTerminationAndTerminate (eNTCP2RouterInfoSignatureVerificationFail);
			return;
		}
		LogPrint(eLogDebug, "NTCP2: SessionConfirmed from ", GetRemoteEndpoint (),
			" (", i2p::data::GetIdentHashAbbreviation (ri.GetIdentHash ()), ")");
		auto ts = i2p::util::GetMillisecondsSinceEpoch ();
		if (ts > ri.GetTimestamp () + i2p::data::NETDB_MIN_EXPIRATION_TIMEOUT*1000LL) // 90 minutes
		{
			LogPrint (eLogError, "NTCP2: RouterInfo is too old in SessionConfirmed for ", (ts - ri.GetTimestamp ())/1000LL, " seconds");
			SendTerminationAndTerminate (eNTCP2Message3Error);
			return;
		}
		if (ts + i2p::data::NETDB_EXPIRATION_TIMEOUT_THRESHOLD*1000LL < ri.GetTimestamp ()) // 2 minutes
		{
			LogPrint (eLogError, "NTCP2: RouterInfo is from future for ", (ri.GetTimestamp () - ts)/1000LL, " seconds");
			SendTerminationAndTerminate (eNTCP2Message3Error);
			return;
		}	
		// update RouterInfo in netdb
		auto ri1 = i2p::data::netdb.AddRouterInfo (ri.GetBuffer (), ri.GetBufferLen ()); // ri1 points to one from netdb now
		if (!ri1)
		{
			LogPrint (eLogError, "NTCP2: Couldn't update RouterInfo from SessionConfirmed in netdb");
			Terminate ();
			return;
		}
		
		bool isOlder = false;
		if (ri.GetTimestamp () + i2p::data::NETDB_EXPIRATION_TIMEOUT_THRESHOLD*1000LL < ri1->GetTimestamp ())
		{	
			// received RouterInfo is older than one in netdb
			isOlder = true;
			if (ri1->HasProfile ())
			{	
				auto profile = i2p::data::GetRouterProfile (ri1->GetIdentHash ()); // retrieve profile	
				if (profile && profile->IsDuplicated ())
				{	
					SendTerminationAndTerminate (eNTCP2Banned);
					return;
				}	
			}	
		}
		
		auto addr = m_RemoteEndpoint.address ().is_v4 () ? ri1->GetNTCP2V4Address () :
			(i2p::util::net::IsYggdrasilAddress (m_RemoteEndpoint.address ()) ? ri1->GetYggdrasilAddress () : ri1->GetNTCP2V6Address ());
		if (!addr || memcmp (m_Establisher->m_RemoteStaticKey, addr->s, 32))
		{
			LogPrint (eLogError, "NTCP2: Wrong static key in SessionConfirmed");
			Terminate ();
			return;
		}
		if (addr->IsPublishedNTCP2 () && m_RemoteEndpoint.address () != addr->host &&
		    (!m_RemoteEndpoint.address ().is_v6 () || (i2p::util::net::IsYggdrasilAddress (m_RemoteEndpoint.address ()) ?
		     memcmp (m_RemoteEndpoint.address ().to_v6 ().to_bytes ().data () + 1, addr->host.to_v6 ().to_bytes ().data () + 1, 7) : // from the same yggdrasil subnet
		     memcmp (m_RemoteEndpoint.address ().to_v6 ().to_bytes ().data (), addr->host.to_v6 ().to_bytes ().data (), 8)))) // temporary address
		{
			if (isOlder) // older router?
				i2p::data::UpdateRouterProfile (ri1->GetIdentHash (),
					[](std::shared_ptr<i2p::data::RouterProfile> profile)
					{
						if (profile) profile->Duplicated (); // mark router as duplicated in profile
					});
			else
				LogPrint (eLogInfo, "NTCP2: Host mismatch between published address ", addr->host, " and actual endpoint ", m_RemoteEndpoint.address ());
			SendTerminationAndTerminate (eNTCP2Banned);
			return;
		}
		// TODO: process options block

		// ready to communicate
		SetRemoteIdentity (ri1->GetRouterIdentity ());
		if (m_Server.AddNTCP2Session (shared_from_this (), true))
		{
			Established ();
			ReceiveLength ();
		}
		else
			Terminate ();
	}	
		
	void NTCP2Session::SetSipKeys (const uint8_t * sendSipKey, const uint8_t * receiveSipKey)
	{
#if OPENSSL_SIPHASH
		EVP_PKEY * sipKey = EVP_PKEY_new_raw_private_key (EVP_PKEY_SIPHASH, nullptr, sendSipKey, 16);
		m_SendMDCtx = EVP_MD_CTX_create ();
		EVP_PKEY_CTX *ctx = nullptr;
		EVP_DigestSignInit (m_SendMDCtx, &ctx, nullptr, nullptr, sipKey);
		EVP_PKEY_CTX_ctrl (ctx, -1, EVP_PKEY_OP_SIGNCTX, EVP_PKEY_CTRL_SET_DIGEST_SIZE, 8, nullptr);
		EVP_PKEY_free (sipKey);

		sipKey = EVP_PKEY_new_raw_private_key (EVP_PKEY_SIPHASH, nullptr, receiveSipKey, 16);
		m_ReceiveMDCtx = EVP_MD_CTX_create ();
		ctx = nullptr;
		EVP_DigestSignInit (m_ReceiveMDCtx, &ctx, NULL, NULL, sipKey);
		EVP_PKEY_CTX_ctrl (ctx, -1, EVP_PKEY_OP_SIGNCTX, EVP_PKEY_CTRL_SET_DIGEST_SIZE, 8, nullptr);
		EVP_PKEY_free (sipKey);
#else
		m_SendSipKey = sendSipKey;
		m_ReceiveSipKey = receiveSipKey;
#endif
	}

	void NTCP2Session::ClientLogin ()
	{
		m_Establisher->CreateEphemeralKey ();
		boost::asio::post (m_Server.GetEstablisherService (), 
		    [s = shared_from_this ()] ()
			{
				s->SendSessionRequest ();
			});	
	}

	void NTCP2Session::ServerLogin ()
	{
		SetTerminationTimeout (NTCP2_ESTABLISH_TIMEOUT);
		SetLastActivityTimestamp (i2p::util::GetSecondsSinceEpoch ());
		boost::asio::async_read (m_Socket, boost::asio::buffer(m_Establisher->m_SessionRequestBuffer, 64), boost::asio::transfer_all (),
			std::bind(&NTCP2Session::HandleSessionRequestReceived, shared_from_this (),
			std::placeholders::_1, std::placeholders::_2));
	}

	void NTCP2Session::ReceiveLength ()
	{
		if (IsTerminated ()) return;
#ifdef __linux__
		const int one = 1;
		setsockopt(m_Socket.native_handle(), IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
#endif
		boost::asio::async_read (m_Socket, boost::asio::buffer(&m_NextReceivedLen, 2), boost::asio::transfer_all (),
			std::bind(&NTCP2Session::HandleReceivedLength, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
	}

	void NTCP2Session::HandleReceivedLength (const boost::system::error_code& ecode, std::size_t bytes_transferred)
	{
		if (ecode)
		{
			if (ecode != boost::asio::error::operation_aborted)
				LogPrint (eLogWarning, "NTCP2: Receive length read error: ", ecode.message ());
			Terminate ();
		}
		else
		{
#if OPENSSL_SIPHASH
			EVP_DigestSignInit (m_ReceiveMDCtx, nullptr, nullptr, nullptr, nullptr);
			EVP_DigestSignUpdate (m_ReceiveMDCtx, m_ReceiveIV.buf, 8);
			size_t l = 8;
			EVP_DigestSignFinal (m_ReceiveMDCtx, m_ReceiveIV.buf, &l);
#else
			i2p::crypto::Siphash<8> (m_ReceiveIV.buf, m_ReceiveIV.buf, 8, m_ReceiveSipKey);
#endif
			// m_NextReceivedLen comes from the network in BigEndian
			m_NextReceivedLen = be16toh (m_NextReceivedLen) ^ le16toh (m_ReceiveIV.key);
			LogPrint (eLogDebug, "NTCP2: Received length ", m_NextReceivedLen);
			if (m_NextReceivedLen >= 16)
			{
				CreateNextReceivedBuffer (m_NextReceivedLen);
				boost::system::error_code ec;
				size_t moreBytes = m_Socket.available(ec);
				if (!ec)
				{	
					if (moreBytes >= m_NextReceivedLen)
					{
						// read and process message immediately if available
						moreBytes = boost::asio::read (m_Socket, boost::asio::buffer(m_NextReceivedBuffer, m_NextReceivedLen), boost::asio::transfer_all (), ec);
						HandleReceived (ec, moreBytes);
					}
					else
						Receive ();
				}	
				else
					LogPrint (eLogWarning, "NTCP2: Socket error: ", ec.message ());
			}
			else
			{
				LogPrint (eLogError, "NTCP2: Received length ", m_NextReceivedLen, " is too short");
				Terminate ();
			}
		}
	}

	void NTCP2Session::Receive ()
	{
		if (IsTerminated ()) return;
#ifdef __linux__
		const int one = 1;
		setsockopt(m_Socket.native_handle(), IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));
#endif
		m_IsReceiving = true;
		boost::asio::async_read (m_Socket, boost::asio::buffer(m_NextReceivedBuffer, m_NextReceivedLen), boost::asio::transfer_all (),
			std::bind(&NTCP2Session::HandleReceived, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
	}

	void NTCP2Session::HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
	{
		if (ecode)
		{
			if (ecode != boost::asio::error::operation_aborted)	
				LogPrint (eLogWarning, "NTCP2: Receive read error: ", ecode.message ());	
			Terminate ();
		}
		else
		{
			UpdateNumReceivedBytes (bytes_transferred + 2);
			i2p::transport::transports.UpdateReceivedBytes (bytes_transferred + 2);
			uint8_t nonce[12];
			CreateNonce (m_ReceiveSequenceNumber, nonce); m_ReceiveSequenceNumber++;
			if (m_Server.AEADChaCha20Poly1305Decrypt (m_NextReceivedBuffer, m_NextReceivedLen-16, nullptr, 0, m_ReceiveKey, nonce, m_NextReceivedBuffer, m_NextReceivedLen))
			{
				LogPrint (eLogDebug, "NTCP2: Received message decrypted");
				ProcessNextFrame (m_NextReceivedBuffer, m_NextReceivedLen-16);
				m_IsReceiving = false;
				ReceiveLength ();
			}
			else
			{
				LogPrint (eLogWarning, "NTCP2: Received AEAD verification failed ");
				SendTerminationAndTerminate (eNTCP2DataPhaseAEADFailure);
			}
		}
	}

	void NTCP2Session::ProcessNextFrame (const uint8_t * frame, size_t len)
	{
		size_t offset = 0;
		while (offset < len)
		{
			uint8_t blk = frame[offset];
			offset++;
			auto size = bufbe16toh (frame + offset);
			offset += 2;
			LogPrint (eLogDebug, "NTCP2: Block type ", (int)blk, " of size ", size);
			if (offset + size > len)
			{
				LogPrint (eLogError, "NTCP2: Unexpected block length ", size);
				break;
			}
			switch (blk)
			{
				case eNTCP2BlkDateTime:
				{
					LogPrint (eLogDebug, "NTCP2: Datetime");
					if (m_IsEstablished)
					{
						uint64_t ts = i2p::util::GetSecondsSinceEpoch ();
						uint64_t tsA = bufbe32toh (frame + offset);
						if (tsA < ts - NTCP2_CLOCK_SKEW || tsA > ts + NTCP2_CLOCK_SKEW)
						{
							LogPrint (eLogWarning, "NTCP2: Established session time difference ", (int)(ts - tsA), " exceeds clock skew");
							SendTerminationAndTerminate (eNTCP2ClockSkew);
						}
					}
					break;
				}
				case eNTCP2BlkOptions:
					LogPrint (eLogDebug, "NTCP2: Options");
				break;
				case eNTCP2BlkRouterInfo:
				{
					LogPrint (eLogDebug, "NTCP2: RouterInfo flag=", (int)frame[offset]);	
					if (size <= i2p::data::MAX_RI_BUFFER_SIZE + 1)
					{		
						auto newRi = i2p::data::netdb.AddRouterInfo (frame + offset + 1, size - 1);
						if (newRi)
						{
							auto remoteIdentity = GetRemoteIdentity ();
							if (remoteIdentity && remoteIdentity->GetIdentHash () == newRi->GetIdentHash ())
								// peer's RouterInfo update
								SetRemoteIdentity (newRi->GetIdentity ());
						}	
					}	
					else
						LogPrint (eLogInfo, "NTCP2: RouterInfo block is too long ", size);
					break;
				}
				case eNTCP2BlkI2NPMessage:
				{
					LogPrint (eLogDebug, "NTCP2: I2NP");
					if (size > I2NP_MAX_MESSAGE_SIZE)
					{
						LogPrint (eLogError, "NTCP2: I2NP block is too long ", size);
						break;
					}
					auto nextMsg = (frame[offset] == eI2NPTunnelData) ? NewI2NPTunnelMessage (true) : NewI2NPMessage (size);
					nextMsg->len = nextMsg->offset + size + 7; // 7 more bytes for full I2NP header
					if (nextMsg->len <= nextMsg->maxLen)
					{
						memcpy (nextMsg->GetNTCP2Header (), frame + offset, size);
						nextMsg->FromNTCP2 ();
						m_Handler.PutNextMessage (std::move (nextMsg));
					}
					else
						LogPrint (eLogError, "NTCP2: I2NP block is too long for I2NP message");
					break;
				}
				case eNTCP2BlkTermination:
					if (size >= 9)
					{
						LogPrint (eLogDebug, "NTCP2: Termination. reason=", (int)(frame[offset + 8]));
						Terminate ();
					}
					else
						LogPrint (eLogWarning, "NTCP2: Unexpected termination block size ", size);
				break;
				case eNTCP2BlkPadding:
					LogPrint (eLogDebug, "NTCP2: Padding");
				break;
				default:
					LogPrint (eLogWarning, "NTCP2: Unknown block type ", (int)blk);
			}
			offset += size;
		}
		m_Handler.Flush ();
	}

	void NTCP2Session::SetNextSentFrameLength (size_t frameLen, uint8_t * lengthBuf)
	{
#if OPENSSL_SIPHASH
		EVP_DigestSignInit (m_SendMDCtx, nullptr, nullptr, nullptr, nullptr);
		EVP_DigestSignUpdate (m_SendMDCtx, m_SendIV.buf, 8);
		size_t l = 8;
		EVP_DigestSignFinal (m_SendMDCtx, m_SendIV.buf, &l);
#else
		i2p::crypto::Siphash<8> (m_SendIV.buf, m_SendIV.buf, 8, m_SendSipKey);
#endif
		// length must be in BigEndian
		htobe16buf (lengthBuf, frameLen ^ le16toh (m_SendIV.key));
		LogPrint (eLogDebug, "NTCP2: Sent length ", frameLen);
	}

	void NTCP2Session::SendI2NPMsgs (std::vector<std::shared_ptr<I2NPMessage> >& msgs)
	{
		if (msgs.empty () || IsTerminated ()) return;

		size_t totalLen = 0;
		std::vector<std::pair<uint8_t *, size_t> > encryptBufs;
		std::vector<boost::asio::const_buffer> bufs;
		std::shared_ptr<I2NPMessage> first;
		uint8_t * macBuf = nullptr;
		for (auto& it: msgs)
		{
			it->ToNTCP2 ();
			auto buf = it->GetNTCP2Header ();
			auto len = it->GetNTCP2Length ();
			// block header
			buf -= 3;
			buf[0] = eNTCP2BlkI2NPMessage; // blk
			htobe16buf (buf + 1, len); // size
			len += 3;
			totalLen += len;
			encryptBufs.push_back ( {buf, len} );
			if (&it == &msgs.front ()) // first message
			{
				// allocate two bytes for length
				buf -= 2; len += 2;
				first = it;
			}
			if (&it == &msgs.back () && it->len + 16 < it->maxLen) // last message
			{
				// if it's long enough we add padding and MAC to it
				// create padding block
				auto paddingLen = CreatePaddingBlock (totalLen, buf + len, it->maxLen - it->len - 16);
				if (paddingLen)
				{
					encryptBufs.push_back ( {buf + len, paddingLen} );
					len += paddingLen;
					totalLen += paddingLen;
				}
				macBuf = buf + len;
				// allocate 16 bytes for MAC
				len += 16;
			}

			bufs.push_back (boost::asio::buffer (buf, len));
		}

		if (!macBuf) // last block was not enough for MAC
		{
			// allocate send buffer
			m_NextSendBuffer = new uint8_t[287]; // can be any size > 16, we just allocate 287 frequently
			// create padding block
			auto paddingLen = CreatePaddingBlock (totalLen, m_NextSendBuffer, 287 - 16);
			// and padding block to encrypt and send
			if (paddingLen)
				encryptBufs.push_back ( {m_NextSendBuffer, paddingLen} );
			bufs.push_back (boost::asio::buffer (m_NextSendBuffer, paddingLen + 16));
			macBuf = m_NextSendBuffer + paddingLen;
			totalLen += paddingLen;
		}
		if (totalLen > NTCP2_UNENCRYPTED_FRAME_MAX_SIZE)
		{
			LogPrint (eLogError, "NTCP2: Frame to send is too long ", totalLen);
			return;
		}	
		uint8_t nonce[12];
		CreateNonce (m_SendSequenceNumber, nonce); m_SendSequenceNumber++;
		m_Server.AEADChaCha20Poly1305Encrypt (encryptBufs, m_SendKey, nonce, macBuf); // encrypt buffers
		SetNextSentFrameLength (totalLen + 16, first->GetNTCP2Header () - 5); // frame length right before first block

		// send buffers
		m_IsSending = true;
		boost::asio::async_write (m_Socket, bufs, boost::asio::transfer_all (),
			std::bind(&NTCP2Session::HandleI2NPMsgsSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2, msgs));
	}

	void NTCP2Session::HandleI2NPMsgsSent (const boost::system::error_code& ecode, std::size_t bytes_transferred, std::vector<std::shared_ptr<I2NPMessage> > msgs)
	{
		HandleNextFrameSent (ecode, bytes_transferred);
		// msgs get destroyed here
	}

	void NTCP2Session::EncryptAndSendNextBuffer (size_t payloadLen)
	{
		if (IsTerminated ())
		{
			delete[] m_NextSendBuffer; m_NextSendBuffer = nullptr;
			return;
		}
		if (payloadLen > NTCP2_UNENCRYPTED_FRAME_MAX_SIZE)
		{
			LogPrint (eLogError, "NTCP2: Buffer to send is too long ", payloadLen);
			delete[] m_NextSendBuffer; m_NextSendBuffer = nullptr;
			return;
		}	
		// encrypt
		uint8_t nonce[12];
		CreateNonce (m_SendSequenceNumber, nonce); m_SendSequenceNumber++;
		m_Server.AEADChaCha20Poly1305Encrypt ({ {m_NextSendBuffer + 2, payloadLen} }, m_SendKey, nonce, m_NextSendBuffer + payloadLen + 2);
		SetNextSentFrameLength (payloadLen + 16, m_NextSendBuffer);
		// send
		m_IsSending = true;
		boost::asio::async_write (m_Socket, boost::asio::buffer (m_NextSendBuffer, payloadLen + 16 + 2), boost::asio::transfer_all (),
			std::bind(&NTCP2Session::HandleNextFrameSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
	}

	void NTCP2Session::HandleNextFrameSent (const boost::system::error_code& ecode, std::size_t bytes_transferred)
	{
		m_IsSending = false;
		delete[] m_NextSendBuffer; m_NextSendBuffer = nullptr;

		if (ecode)
		{
			if (ecode != boost::asio::error::operation_aborted)
				LogPrint (eLogWarning, "NTCP2: Couldn't send frame ", ecode.message ());
			Terminate ();
		}
		else
		{
			UpdateNumSentBytes (bytes_transferred);
			i2p::transport::transports.UpdateSentBytes (bytes_transferred);
			LogPrint (eLogDebug, "NTCP2: Next frame sent ", bytes_transferred);
			if (GetLastActivityTimestamp () > m_NextRouterInfoResendTime)
			{
				m_NextRouterInfoResendTime += NTCP2_ROUTERINFO_RESEND_INTERVAL +
					m_Server.GetRng ()() % NTCP2_ROUTERINFO_RESEND_INTERVAL_THRESHOLD;
				SendRouterInfo ();
			}
			else
			{
				SendQueue ();
				SetSendQueueSize (m_SendQueue.size ());
			}
		}
	}

	void NTCP2Session::SendQueue ()
	{
		if (!m_SendQueue.empty () && m_IsEstablished)
		{
			std::vector<std::shared_ptr<I2NPMessage> > msgs;
			auto ts = i2p::util::GetMillisecondsSinceEpoch ();
			size_t s = 0;
			while (!m_SendQueue.empty ())
			{
				auto msg = m_SendQueue.front ();
				if (!msg || msg->IsExpired (ts))
				{
					// drop null or expired message
					if (msg) msg->Drop ();
					m_SendQueue.pop_front ();
					continue;
				}	
				size_t len = msg->GetNTCP2Length ();
				if (s + len + 3 <= NTCP2_UNENCRYPTED_FRAME_MAX_SIZE) // 3 bytes block header
				{
					msgs.push_back (msg);
					s += (len + 3);
					m_SendQueue.pop_front ();
					if (s >= NTCP2_SEND_AFTER_FRAME_SIZE)
						break; // send frame right a way
				}
				else if (len + 3 > NTCP2_UNENCRYPTED_FRAME_MAX_SIZE)
				{
					LogPrint (eLogError, "NTCP2: I2NP message of size ", len, " can't be sent. Dropped");
					msg->Drop ();
					m_SendQueue.pop_front ();
				}
				else
					break;
			}
			SendI2NPMsgs (msgs);
		}
	}

	void NTCP2Session::MoveSendQueue (std::shared_ptr<NTCP2Session> other)
	{
		if (!other || m_SendQueue.empty ()) return;
		std::list<std::shared_ptr<I2NPMessage> > msgs;
		auto ts = i2p::util::GetMillisecondsSinceEpoch ();
		for (auto it: m_SendQueue)
			if (!it->IsExpired (ts))
				msgs.push_back (it);
			else
				it->Drop ();
		m_SendQueue.clear ();
		if (!msgs.empty ())
			other->SendI2NPMessages (msgs);
	}	
		
	size_t NTCP2Session::CreatePaddingBlock (size_t msgLen, uint8_t * buf, size_t len)
	{
		if (len < 3) return 0;
		len -= 3;
		if (msgLen < 256) msgLen = 256; // for short message padding should not be always zero
		size_t paddingSize = (msgLen*NTCP2_MAX_PADDING_RATIO)/100;
		if (msgLen + paddingSize + 3 > NTCP2_UNENCRYPTED_FRAME_MAX_SIZE) 
		{	
			int l = (int)NTCP2_UNENCRYPTED_FRAME_MAX_SIZE - msgLen -3;
			if (l <= 0) return 0;
			paddingSize = l;
		}	
		if (paddingSize > len) paddingSize = len;
		if (paddingSize)
		{
			if (m_NextPaddingSize >= 16)
			{
				RAND_bytes ((uint8_t *)m_PaddingSizes, sizeof (m_PaddingSizes));
				m_NextPaddingSize = 0;
			}
			paddingSize = m_PaddingSizes[m_NextPaddingSize++] % (paddingSize + 1);
		}
		buf[0] = eNTCP2BlkPadding; // blk
		htobe16buf (buf + 1, paddingSize); // size
		memset (buf + 3, 0, paddingSize);
		return paddingSize + 3;
	}

	void NTCP2Session::SendRouterInfo ()
	{
		if (!IsEstablished ()) return;
		auto riBuffer =  i2p::context.CopyRouterInfoBuffer ();
		auto riLen = riBuffer->GetBufferLen ();
		size_t payloadLen = riLen + 3 + 1 + 7; // 3 bytes block header + 1 byte RI flag + 7 bytes DateTime
		m_NextSendBuffer = new uint8_t[payloadLen + 16 + 2 + 64]; // up to 64 bytes padding
		// DateTime	block
		m_NextSendBuffer[2] = eNTCP2BlkDateTime;
		htobe16buf (m_NextSendBuffer + 3, 4);
		htobe32buf (m_NextSendBuffer + 5, (i2p::util::GetMillisecondsSinceEpoch () + 500)/1000);
		// RouterInfo block
		m_NextSendBuffer[9] = eNTCP2BlkRouterInfo;
		htobe16buf (m_NextSendBuffer + 10, riLen + 1); // size
		m_NextSendBuffer[12] = 0; // flag
		memcpy (m_NextSendBuffer + 13, riBuffer->data (), riLen); // TODO: eliminate extra copy
		// padding block
		auto paddingSize = CreatePaddingBlock (payloadLen, m_NextSendBuffer + 2 + payloadLen, 64);
		payloadLen += paddingSize;
		// encrypt and send
		EncryptAndSendNextBuffer (payloadLen);
	}

	void NTCP2Session::SendTermination (NTCP2TerminationReason reason)
	{
		if (!m_SendKey ||
#if OPENSSL_SIPHASH
			!m_SendMDCtx
#else
			!m_SendSipKey
#endif
		) return;
		m_NextSendBuffer = new uint8_t[49]; // 49 = 12 bytes message + 16 bytes MAC + 2 bytes size + up to 19 padding block
		// termination block
		m_NextSendBuffer[2] = eNTCP2BlkTermination;
		m_NextSendBuffer[3] = 0; m_NextSendBuffer[4] = 9; // 9 bytes block size
		htobe64buf (m_NextSendBuffer + 5, m_ReceiveSequenceNumber);
		m_NextSendBuffer[13] = (uint8_t)reason;
		// padding block
		auto paddingSize = CreatePaddingBlock (12, m_NextSendBuffer + 14, 19);
		// encrypt and send
		EncryptAndSendNextBuffer (paddingSize + 12);
	}

	void NTCP2Session::SendTerminationAndTerminate (NTCP2TerminationReason reason)
	{
		SendTermination (reason);
		boost::asio::post (m_Server.GetService (), std::bind (&NTCP2Session::Terminate, shared_from_this ())); // let termination message go
	}

	void NTCP2Session::ReadSomethingAndTerminate ()
	{
		size_t len = m_Server.GetRng ()() % NTCP2_SESSION_REQUEST_MAX_SIZE;
		if (len > 0 && m_Establisher)
			boost::asio::async_read (m_Socket, boost::asio::buffer(m_Establisher->m_SessionRequestBuffer, len), boost::asio::transfer_all (),
				[s = shared_from_this()](const boost::system::error_code& ecode, size_t bytes_transferred)
			    { 
					s->Terminate ();
				});
		else
			boost::asio::post (m_Server.GetService (), std::bind (&NTCP2Session::Terminate, shared_from_this ()));
	}	
		
	void NTCP2Session::SendI2NPMessages (std::list<std::shared_ptr<I2NPMessage> >& msgs)
	{
		if (m_IsTerminated || msgs.empty ()) 
		{
			msgs.clear ();
			return;
		}	
		bool empty = false;
		{
			std::lock_guard<std::mutex> l(m_IntermediateQueueMutex);
			empty = m_IntermediateQueue.empty ();
			m_IntermediateQueue.splice (m_IntermediateQueue.end (), msgs);
		}
		if (empty)
			boost::asio::post (m_Server.GetService (), std::bind (&NTCP2Session::PostI2NPMessages, shared_from_this ()));
	}

	void NTCP2Session::PostI2NPMessages ()
	{
		if (m_IsTerminated) return;
		std::list<std::shared_ptr<I2NPMessage> > msgs;
		{
			std::lock_guard<std::mutex> l(m_IntermediateQueueMutex);
			m_IntermediateQueue.swap (msgs);		
		}	
		bool isSemiFull = m_SendQueue.size () > NTCP2_MAX_OUTGOING_QUEUE_SIZE/2;
		if (isSemiFull)
		{	
			for (auto it: msgs)
				if (it->onDrop)
					it->Drop (); // drop earlier because we can handle it
				else
					m_SendQueue.push_back (std::move (it));
		}	
		else
			m_SendQueue.splice (m_SendQueue.end (), msgs);
		
		if (!m_IsSending && m_IsEstablished)
			SendQueue ();
		else if (m_SendQueue.size () > NTCP2_MAX_OUTGOING_QUEUE_SIZE)
		{
			LogPrint (eLogWarning, "NTCP2: Outgoing messages queue size to ",
				GetIdentHashBase64(), " exceeds ", NTCP2_MAX_OUTGOING_QUEUE_SIZE);
			Terminate ();
		}
		SetSendQueueSize (m_SendQueue.size ());
	}

	void NTCP2Session::SendLocalRouterInfo (bool update)
	{
		if (update || !IsOutgoing ()) // we send it in SessionConfirmed for outgoing session
			boost::asio::post (m_Server.GetService (), std::bind (&NTCP2Session::SendRouterInfo, shared_from_this ()));
	}

	i2p::data::RouterInfo::SupportedTransports NTCP2Session::GetTransportType () const
	{
		if (m_RemoteEndpoint.address ().is_v4 ()) return i2p::data::RouterInfo::eNTCP2V4;
		return i2p::util::net::IsYggdrasilAddress (m_RemoteEndpoint.address ()) ? i2p::data::RouterInfo::eNTCP2V6Mesh : i2p::data::RouterInfo::eNTCP2V6;
	}	
		
	NTCP2Server::NTCP2Server ():
		RunnableServiceWithWork ("NTCP2"), m_TerminationTimer (GetService ()),
		m_ProxyType(eNoProxy), m_Resolver(GetService ()),
		m_Rng(i2p::util::GetMonotonicMicroseconds ()%1000000LL)
	{
	}

	NTCP2Server::~NTCP2Server ()
	{
		Stop ();
	}

	void NTCP2Server::Start ()
	{
		m_EstablisherService.Start ();
		if (!IsRunning ())
		{
			StartIOService ();
			if(UsingProxy())
			{
				LogPrint(eLogInfo, "NTCP2: Using proxy to connect to peers");
				// TODO: resolve proxy until it is resolved
				boost::system::error_code e;
				auto itr = m_Resolver.resolve(m_ProxyAddress, std::to_string(m_ProxyPort), e);
				if(e)
					LogPrint(eLogCritical, "NTCP2: Failed to resolve proxy ", e.message());
				else
				{
					m_ProxyEndpoint.reset (new boost::asio::ip::tcp::endpoint(*itr.begin ()));
					if (m_ProxyEndpoint)
						LogPrint(eLogDebug, "NTCP2: m_ProxyEndpoint ", *m_ProxyEndpoint);
				}
			}
			else
				LogPrint(eLogInfo, "NTCP2: Proxy is not used");
			// start acceptors
			auto addresses = context.GetRouterInfo ().GetAddresses ();
			if (!addresses) return;
			for (const auto& address: *addresses)
			{
				if (!address) continue;
				if (address->IsPublishedNTCP2 () && address->port)
				{
					if (address->IsV4())
					{
						try
						{
							auto ep = m_Address4 ? boost::asio::ip::tcp::endpoint (m_Address4->address(), address->port):
								boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), address->port);
							m_NTCP2Acceptor.reset (new boost::asio::ip::tcp::acceptor (GetService (), ep));
						}
						catch ( std::exception & ex )
						{
							LogPrint(eLogCritical, "NTCP2: Failed to bind to v4 port ", address->port, ex.what());
							ThrowFatal ("Unable to start IPv4 NTCP2 transport at port ", address->port, ": ", ex.what ());
							continue;
						}

						LogPrint (eLogInfo, "NTCP2: Start listening v4 TCP port ", address->port);
						auto conn = std::make_shared<NTCP2Session>(*this);
						m_NTCP2Acceptor->async_accept(conn->GetSocket (), std::bind (&NTCP2Server::HandleAccept, this, conn, std::placeholders::_1));
					}
					else if (address->IsV6() && (context.SupportsV6 () || context.SupportsMesh ()))
					{
						m_NTCP2V6Acceptor.reset (new boost::asio::ip::tcp::acceptor (GetService ()));
						try
						{
							m_NTCP2V6Acceptor->open (boost::asio::ip::tcp::v6());
							m_NTCP2V6Acceptor->set_option (boost::asio::ip::v6_only (true));
							m_NTCP2V6Acceptor->set_option (boost::asio::socket_base::reuse_address (true));
#if defined(__linux__) && !defined(_NETINET_IN_H)
							if (!m_Address6 && !m_YggdrasilAddress) // only if not binded to address
							{
								// Set preference to use public IPv6 address -- tested on linux, not works on windows, and not tested on others
#if (BOOST_VERSION >= 105500)
								typedef boost::asio::detail::socket_option::integer<BOOST_ASIO_OS_DEF(IPPROTO_IPV6), IPV6_ADDR_PREFERENCES> ipv6PreferAddr;
#else
								typedef boost::asio::detail::socket_option::integer<IPPROTO_IPV6, IPV6_ADDR_PREFERENCES> ipv6PreferAddr;
#endif
								m_NTCP2V6Acceptor->set_option (ipv6PreferAddr(IPV6_PREFER_SRC_PUBLIC | IPV6_PREFER_SRC_HOME | IPV6_PREFER_SRC_NONCGA));
							}
#endif
							auto ep = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), address->port);
							if (m_Address6 && !context.SupportsMesh ())
								ep = boost::asio::ip::tcp::endpoint (m_Address6->address(), address->port);
							else if (m_YggdrasilAddress && !context.SupportsV6 ())
								ep = boost::asio::ip::tcp::endpoint (m_YggdrasilAddress->address(), address->port);
							m_NTCP2V6Acceptor->bind (ep);
							m_NTCP2V6Acceptor->listen ();

							LogPrint (eLogInfo, "NTCP2: Start listening v6 TCP port ", address->port);
							auto conn = std::make_shared<NTCP2Session> (*this);
							m_NTCP2V6Acceptor->async_accept(conn->GetSocket (), std::bind (&NTCP2Server::HandleAcceptV6, this, conn, std::placeholders::_1));
						}
						catch ( std::exception & ex )
						{
							LogPrint(eLogCritical, "NTCP2: Failed to bind to v6 port ", address->port, ": ", ex.what());
							ThrowFatal ("Unable to start IPv6 NTCP2 transport at port ", address->port, ": ", ex.what ());
							continue;
						}
					}
				}
			}
			ScheduleTermination ();
		}
	}

	void NTCP2Server::Stop ()
	{
		m_EstablisherService.Stop ();
		{
			// we have to copy it because Terminate changes m_NTCP2Sessions
			auto ntcpSessions = m_NTCP2Sessions;
			for (auto& it: ntcpSessions)
				it.second->Terminate ();
			for (auto& it: m_PendingIncomingSessions)
				it.second->Terminate ();
		}
		m_NTCP2Sessions.clear ();

		if (IsRunning ())
		{
			m_TerminationTimer.cancel ();
			m_ProxyEndpoint = nullptr;
		}
		StopIOService ();
	}

	bool NTCP2Server::AddNTCP2Session (std::shared_ptr<NTCP2Session> session, bool incoming)
	{
		if (!session) return false;
		if (incoming)
			m_PendingIncomingSessions.erase (session->GetRemoteEndpoint ().address ());
		if (!session->GetRemoteIdentity ())
		{
			LogPrint (eLogWarning, "NTCP2: Unknown identity for ", session->GetRemoteEndpoint ());
			session->Terminate ();
			return false;
		}
		auto& ident = session->GetRemoteIdentity ()->GetIdentHash ();
		auto it = m_NTCP2Sessions.find (ident);
		if (it != m_NTCP2Sessions.end ())
		{
			LogPrint (eLogWarning, "NTCP2: Session with ", ident.ToBase64 (), " already exists. ", incoming ? "Replaced" : "Dropped");
			if (incoming)
			{
				// replace by new session
				auto s = it->second;
				s->MoveSendQueue (session);
				m_NTCP2Sessions.erase (it);
				s->Terminate ();
			}
			else
			{
				session->Terminate ();
				return false;
			}
		}
		m_NTCP2Sessions.emplace (ident, session);
		return true;
	}

	void NTCP2Server::RemoveNTCP2Session (std::shared_ptr<NTCP2Session> session)
	{
		if (session && session->GetRemoteIdentity ())
		{
			auto it = m_NTCP2Sessions.find (session->GetRemoteIdentity ()->GetIdentHash ());
			if (it != m_NTCP2Sessions.end () && it->second == session)
				m_NTCP2Sessions.erase (it);
		}	
	}

	std::shared_ptr<NTCP2Session> NTCP2Server::FindNTCP2Session (const i2p::data::IdentHash& ident)
	{
		auto it = m_NTCP2Sessions.find (ident);
		if (it != m_NTCP2Sessions.end ())
			return it->second;
		return nullptr;
	}

	void NTCP2Server::Connect(std::shared_ptr<NTCP2Session> conn)
	{
		if (!conn || conn->GetRemoteEndpoint ().address ().is_unspecified ())
		{
			LogPrint (eLogError, "NTCP2: Can't connect to unspecified address");
			return;
		}
		LogPrint (eLogDebug, "NTCP2: Connecting to ", conn->GetRemoteEndpoint (),
			" (", i2p::data::GetIdentHashAbbreviation (conn->GetRemoteIdentity ()->GetIdentHash ()), ")");
		boost::asio::post (GetService (), [this, conn]()
			{
				if (this->AddNTCP2Session (conn))
				{
					auto timer = std::make_shared<boost::asio::deadline_timer>(GetService ());
					auto timeout = NTCP2_CONNECT_TIMEOUT * 5;
					conn->SetTerminationTimeout(timeout * 2);
					timer->expires_from_now (boost::posix_time::seconds(timeout));
					timer->async_wait ([conn, timeout](const boost::system::error_code& ecode)
					{
						if (ecode != boost::asio::error::operation_aborted)
						{
							LogPrint (eLogInfo, "NTCP2: Not connected in ", timeout, " seconds");
							conn->Terminate ();
						}
					});
					// bind to local address
					std::shared_ptr<boost::asio::ip::tcp::endpoint> localAddress;
					if (conn->GetRemoteEndpoint ().address ().is_v6 ())
					{
						if (i2p::util::net::IsYggdrasilAddress (conn->GetRemoteEndpoint ().address ()))
							localAddress = m_YggdrasilAddress;
						else
							localAddress = m_Address6;
						conn->GetSocket ().open (boost::asio::ip::tcp::v6 ());
					}
					else
					{
						localAddress = m_Address4;
						conn->GetSocket ().open (boost::asio::ip::tcp::v4 ());
					}
					if (localAddress)
					{
						boost::system::error_code ec;
						conn->GetSocket ().bind (*localAddress, ec);
						if (ec)
							LogPrint (eLogError, "NTCP2: Can't bind to ", localAddress->address ().to_string (), ": ", ec.message ());
					}
					conn->GetSocket ().async_connect (conn->GetRemoteEndpoint (), std::bind (&NTCP2Server::HandleConnect, this, std::placeholders::_1, conn, timer));
				}
				else
					conn->Terminate ();
			});
	}

	void NTCP2Server::HandleConnect (const boost::system::error_code& ecode, std::shared_ptr<NTCP2Session> conn, std::shared_ptr<boost::asio::deadline_timer> timer)
	{
		timer->cancel ();
		if (ecode)
		{
			LogPrint (eLogInfo, "NTCP2: Connect error ", ecode.message ());
			conn->Terminate ();
		}
		else
		{
			LogPrint (eLogDebug, "NTCP2: Connected to ", conn->GetRemoteEndpoint (),
				" (", i2p::data::GetIdentHashAbbreviation (conn->GetRemoteIdentity ()->GetIdentHash ()), ")");
			conn->ClientLogin ();
		}
	}

	void NTCP2Server::HandleAccept (std::shared_ptr<NTCP2Session> conn, const boost::system::error_code& error)
	{
		if (!error && conn)
		{
			boost::system::error_code ec;
			auto ep = conn->GetSocket ().remote_endpoint(ec);
			if (!ec)
			{
				LogPrint (eLogDebug, "NTCP2: Connected from ", ep);
				if (!i2p::transport::transports.IsInReservedRange(ep.address ()))
				{
					if (m_PendingIncomingSessions.emplace (ep.address (), conn).second)
					{
						conn->SetRemoteEndpoint (ep);
						conn->ServerLogin ();
						conn = nullptr;
					}
					else
						LogPrint (eLogInfo, "NTCP2: Incoming session from ", ep.address (), " is already pending");
				}
				else
					LogPrint (eLogError, "NTCP2: Incoming connection from invalid IP ", ep.address ());
			}
			else
				LogPrint (eLogError, "NTCP2: Connected from error ", ec.message ());
		}
		else
		{
			LogPrint (eLogError, "NTCP2: Accept error ", error.message ());
			if (error == boost::asio::error::no_descriptors)
			{
				i2p::context.SetError (eRouterErrorNoDescriptors);
				return;
			}
		}

		if (error != boost::asio::error::operation_aborted)
		{
			if (!conn) // connection is used, create new one
				conn = std::make_shared<NTCP2Session> (*this);
			else // reuse failed
				conn->Close ();
			m_NTCP2Acceptor->async_accept(conn->GetSocket (), std::bind (&NTCP2Server::HandleAccept, this,
				conn, std::placeholders::_1));
		}
	}

	void NTCP2Server::HandleAcceptV6 (std::shared_ptr<NTCP2Session> conn, const boost::system::error_code& error)
	{
		if (!error && conn)
		{
			boost::system::error_code ec;
			auto ep = conn->GetSocket ().remote_endpoint(ec);
			if (!ec)
			{
				LogPrint (eLogDebug, "NTCP2: Connected from ", ep);
				if (!i2p::transport::transports.IsInReservedRange(ep.address ()) ||
				    i2p::util::net::IsYggdrasilAddress (ep.address ()))
				{
					if (m_PendingIncomingSessions.emplace (ep.address (), conn).second)
					{
						conn->SetRemoteEndpoint (ep);
						conn->ServerLogin ();
						conn = nullptr;
					}
					else
						LogPrint (eLogInfo, "NTCP2: Incoming session from ", ep.address (), " is already pending");
				}
				else
					LogPrint (eLogError, "NTCP2: Incoming connection from invalid IP ", ep.address ());
			}
			else
				LogPrint (eLogError, "NTCP2: Connected from error ", ec.message ());
		}
		else
		{
			LogPrint (eLogError, "NTCP2: Accept ipv6 error ", error.message ());
			if (error == boost::asio::error::no_descriptors)
			{
				i2p::context.SetErrorV6 (eRouterErrorNoDescriptors);
				return;
			}
		}

		if (error != boost::asio::error::operation_aborted)
		{
			if (!conn) // connection is used, create new one
				conn = std::make_shared<NTCP2Session> (*this);
			else // reuse failed
				conn->Close ();
			m_NTCP2V6Acceptor->async_accept(conn->GetSocket (), std::bind (&NTCP2Server::HandleAcceptV6, this,
				conn, std::placeholders::_1));
		}
	}

	void NTCP2Server::ScheduleTermination ()
	{
		m_TerminationTimer.expires_from_now (boost::posix_time::seconds(
			NTCP2_TERMINATION_CHECK_TIMEOUT + m_Rng () % NTCP2_TERMINATION_CHECK_TIMEOUT_VARIANCE));
		m_TerminationTimer.async_wait (std::bind (&NTCP2Server::HandleTerminationTimer,
			this, std::placeholders::_1));
	}

	void NTCP2Server::HandleTerminationTimer (const boost::system::error_code& ecode)
	{
		if (ecode != boost::asio::error::operation_aborted)
		{
			auto ts = i2p::util::GetSecondsSinceEpoch ();
			// established
			for (auto& it: m_NTCP2Sessions)
				if (it.second->IsTerminationTimeoutExpired (ts))
				{
					auto session = it.second;
					LogPrint (eLogDebug, "NTCP2: No activity for ", session->GetTerminationTimeout (), " seconds");
					session->TerminateByTimeout (); // it doesn't change m_NTCP2Session right a way
				}
				else
					it.second->DeleteNextReceiveBuffer (ts);
			// pending
			for (auto it = m_PendingIncomingSessions.begin (); it != m_PendingIncomingSessions.end ();)
			{
				if (it->second->IsEstablished () || it->second->IsTerminationTimeoutExpired (ts))
				{
					it->second->Terminate ();
					it = m_PendingIncomingSessions.erase (it); // established of expired
				}
				else if (it->second->IsTerminated ())
					it = m_PendingIncomingSessions.erase (it); // already terminated
				else
					it++;
			}
			ScheduleTermination ();

			// try to restart acceptors if no description
			// we do it after timer to let timer take descriptor first
			if (i2p::context.GetError () == eRouterErrorNoDescriptors)
			{
				i2p::context.SetError (eRouterErrorNone);
				auto conn = std::make_shared<NTCP2Session> (*this);
				m_NTCP2Acceptor->async_accept(conn->GetSocket (), std::bind (&NTCP2Server::HandleAccept, this,
					conn, std::placeholders::_1));
			}
			if (i2p::context.GetErrorV6 () == eRouterErrorNoDescriptors)
			{
				i2p::context.SetErrorV6 (eRouterErrorNone);
				auto conn = std::make_shared<NTCP2Session> (*this);
				m_NTCP2V6Acceptor->async_accept(conn->GetSocket (), std::bind (&NTCP2Server::HandleAcceptV6, this,
					conn, std::placeholders::_1));
			}
		}
	}

	void NTCP2Server::ConnectWithProxy (std::shared_ptr<NTCP2Session> conn)
	{
		if(!m_ProxyEndpoint) return;
		if (!conn || conn->GetRemoteEndpoint ().address ().is_unspecified ())
		{
			LogPrint (eLogError, "NTCP2: Can't connect to unspecified address");
			return;
		}
		boost::asio::post (GetService(), [this, conn]()
		{
			if (this->AddNTCP2Session (conn))
			{
				auto timer = std::make_shared<boost::asio::deadline_timer>(GetService());
				auto timeout = NTCP2_CONNECT_TIMEOUT * 5;
				conn->SetTerminationTimeout(timeout * 2);
				timer->expires_from_now (boost::posix_time::seconds(timeout));
				timer->async_wait ([conn, timeout](const boost::system::error_code& ecode)
				{
					if (ecode != boost::asio::error::operation_aborted)
					{
						LogPrint (eLogInfo, "NTCP2: Not connected in ", timeout, " seconds");
						conn->Terminate ();
					}
				});
				conn->GetSocket ().async_connect (*m_ProxyEndpoint, std::bind (&NTCP2Server::HandleProxyConnect, this, std::placeholders::_1, conn, timer));
			}
		});
	}

	void NTCP2Server::UseProxy(ProxyType proxytype, const std::string& addr, uint16_t port,
		const std::string& user, const std::string& pass)
	{
		m_ProxyType = proxytype;
		m_ProxyAddress = addr;
		m_ProxyPort = port;
		if (m_ProxyType == eHTTPProxy )
			m_ProxyAuthorization = i2p::http::CreateBasicAuthorizationString (user, pass);
	}

	void NTCP2Server::HandleProxyConnect(const boost::system::error_code& ecode, std::shared_ptr<NTCP2Session> conn, std::shared_ptr<boost::asio::deadline_timer> timer)
	{
		if (ecode)
		{
			LogPrint(eLogWarning, "NTCP2: Failed to connect to proxy ", ecode.message());
			timer->cancel();
			conn->Terminate();
			return;
		}
		switch (m_ProxyType)
		{
			case eSocksProxy:
			{
				// TODO: support username/password auth etc
				Socks5Handshake (conn->GetSocket(), conn->GetRemoteEndpoint (),
					[conn, timer](const boost::system::error_code& ec)
				    {
						timer->cancel();
						if (!ec)
							conn->ClientLogin();
						else
						{
							LogPrint(eLogError, "NTCP2: SOCKS proxy handshake error ", ec.message());
							conn->Terminate();	
						}		
					});	
				break;
			}
			case eHTTPProxy:
			{
				auto& ep = conn->GetRemoteEndpoint ();
				i2p::http::HTTPReq req;
				req.method = "CONNECT";
				req.version ="HTTP/1.1";
				if(ep.address ().is_v6 ())
					req.uri = "[" + ep.address ().to_string() + "]:" + std::to_string(ep.port ());
				else
					req.uri = ep.address ().to_string() + ":" + std::to_string(ep.port ());
				if (!m_ProxyAuthorization.empty ())
					req.AddHeader("Proxy-Authorization", m_ProxyAuthorization);

				boost::asio::streambuf writebuff;
				std::ostream out(&writebuff);
				out << req.to_string();

				boost::asio::async_write(conn->GetSocket(), writebuff.data(), boost::asio::transfer_all(),
					[](const boost::system::error_code & ec, std::size_t transferred)
					{
						(void) transferred;
						if(ec)
							LogPrint(eLogError, "NTCP2: HTTP proxy write error ", ec.message());
					});

				auto readbuff = std::make_shared<boost::asio::streambuf>();
				boost::asio::async_read_until(conn->GetSocket(), *readbuff, "\r\n\r\n",
					[readbuff, timer, conn] (const boost::system::error_code & ec, std::size_t transferred)
					{
						if(ec)
						{
							LogPrint(eLogError, "NTCP2: HTTP proxy read error ", ec.message());
							timer->cancel();
							conn->Terminate();
						}
						else
						{
							readbuff->commit(transferred);
							i2p::http::HTTPRes res;
							if(res.parse(std::string {boost::asio::buffers_begin(readbuff->data ()), boost::asio::buffers_begin(readbuff->data ()) + readbuff->size ()}) > 0)
							{
								if(res.code == 200)
								{
									timer->cancel();
									conn->ClientLogin();
									return;
								}
								else
									LogPrint(eLogError, "NTCP2: HTTP proxy rejected request ", res.code);
							}
							else
								LogPrint(eLogError, "NTCP2: HTTP proxy gave malformed response");
							timer->cancel();
							conn->Terminate();
						}
					});
				break;
			}
			default:
				LogPrint(eLogError, "NTCP2: Unknown proxy type, invalid state");
		}
	}

	void NTCP2Server::SetLocalAddress (const boost::asio::ip::address& localAddress)
	{
		auto addr = std::make_shared<boost::asio::ip::tcp::endpoint>(boost::asio::ip::tcp::endpoint(localAddress, 0));
		if (localAddress.is_v6 ())
		{
			if (i2p::util::net::IsYggdrasilAddress (localAddress))
				m_YggdrasilAddress = addr;
			else
				m_Address6 = addr;
		}
		else
			m_Address4 = addr;
	}

	void NTCP2Server::AEADChaCha20Poly1305Encrypt (const std::vector<std::pair<uint8_t *, size_t> >& bufs, 
		const uint8_t * key, const uint8_t * nonce, uint8_t * mac)
	{
		return m_Encryptor.Encrypt (bufs, key, nonce, mac);
	}	
		
	bool NTCP2Server::AEADChaCha20Poly1305Decrypt (const uint8_t * msg, size_t msgLen,
		const uint8_t * ad, size_t adLen, const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len)
	{
		return m_Decryptor.Decrypt (msg, msgLen, ad, adLen, key, nonce, buf, len);
	}	
}
}