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
|
// Copyright (c) 2009 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#pragma push_macro("snprintf")
#undef snprintf
#include <nlohmann/json.hpp>
#pragma pop_macro("snprintf")
#ifdef snprintf
#undef snprintf
#endif
#include "headers.h"
#ifdef _WIN32
#include <winsock2.h>
#endif
#include <openssl/rand.h>
#include "btfaddr.h"
#include "btftunnel.h"
void ThreadReconnectCachedBtfPeers(void* parg);
void ThreadMessageHandler2(void* parg);
void ThreadSocketHandler2(void* parg);
//
// Global state variables
//
bool fClient = false;
uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);
CAddress addrLocalHost(0, DEFAULT_PORT, nLocalServices);
unsigned short nListenPort = DEFAULT_PORT; // local P2P port (tunable via /port)
CNode nodeLocalHost(INVALID_SOCKET, CAddress("127.0.0.1", nLocalServices));
CNode* pnodeLocalHost = &nodeLocalHost;
bool fShutdown = false;
array<bool, 10> vfThreadRunning;
vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
map<CInv, CDataStream> mapRelay;
deque<pair<int64, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
map<CInv, int64> mapAlreadyAskedFor;
string strBtfConnect; // .btf peer to keep connected to (from /connectbtf)
bool GetMyExternalIP(unsigned int& ipRet)
{
// Try several plain-text IP echo services in order.
// Each returns just the IPv4 address as the first line of the HTTP body.
struct { const char* host; const char* path; } services[] = {
{ "api4.ipify.org", "/" },
{ "icanhazip.com", "/" },
{ "ipecho.net", "/plain" },
{ "checkip.amazonaws.com", "/" },
};
for (auto& svc : services)
{
struct addrinfo hints, *res = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(svc.host, "80", &hints, &res) != 0 || !res)
continue;
SOCKET hSocket = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (hSocket == INVALID_SOCKET) { freeaddrinfo(res); continue; }
// 5-second timeout so a dead service doesn't stall startup
#ifdef _WIN32
DWORD tv = 5000;
setsockopt(hSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(tv));
setsockopt(hSocket, SOL_SOCKET, SO_SNDTIMEO, (const char*)&tv, sizeof(tv));
#else
struct timeval tv; tv.tv_sec = 5; tv.tv_usec = 0;
setsockopt(hSocket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
setsockopt(hSocket, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
#endif
if (connect(hSocket, res->ai_addr, (int)res->ai_addrlen) != 0)
{
freeaddrinfo(res); closesocket(hSocket); continue;
}
freeaddrinfo(res);
string req = string("GET ") + svc.path + " HTTP/1.0\r\nHost: " + svc.host + "\r\nConnection: close\r\n\r\n";
send(hSocket, req.c_str(), (int)req.size(), 0);
// Read response, skip HTTP headers, grab first line of body
string response;
char buf[256];
int n;
while ((n = recv(hSocket, buf, sizeof(buf)-1, 0)) > 0)
{
buf[n] = 0;
response += buf;
if (response.size() > 4096) break;
}
closesocket(hSocket);
// Find blank line separating headers from body
size_t bodyPos = response.find("\r\n\r\n");
if (bodyPos == string::npos) bodyPos = response.find("\n\n");
if (bodyPos == string::npos) continue;
string body = response.substr(bodyPos + (response[bodyPos+2]=='\r' ? 4 : 2));
// Trim whitespace
while (!body.empty() && (body.back() == '\n' || body.back() == '\r' || body.back() == ' '))
body.pop_back();
// Parse as IP
CAddress addr(body.c_str());
if (addr.ip == 0) continue;
printf("GetMyExternalIP() via %s: %s\n", svc.host, body.c_str());
ipRet = addr.ip;
return true;
}
return error("GetMyExternalIP() : all services failed\n");
}
void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1)
{
// If the dialog might get closed before the reply comes back,
// call this in the destructor so it doesn't get called after it's deleted.
CRITICAL_BLOCK(cs_vNodes)
{
foreach(CNode* pnode, vNodes)
{
CRITICAL_BLOCK(pnode->cs_mapRequests)
{
for (map<uint256, CRequestTracker>::iterator mi = pnode->mapRequests.begin(); mi != pnode->mapRequests.end();)
{
CRequestTracker& tracker = (*mi).second;
if (tracker.fn == fn && tracker.param1 == param1)
pnode->mapRequests.erase(mi++);
else
mi++;
}
}
}
}
}
//
// Subscription methods for the broadcast and subscription system.
// Channel numbers are message numbers, i.e. MSG_TABLE and MSG_PRODUCT.
//
// The subscription system uses a meet-in-the-middle strategy.
// With 100,000 nodes, if senders broadcast to 1000 random nodes and receivers
// subscribe to 1000 random nodes, 99.995% (1 - 0.99^1000) of messages will get through.
//
bool AnySubscribed(unsigned int nChannel)
{
if (pnodeLocalHost->IsSubscribed(nChannel))
return true;
CRITICAL_BLOCK(cs_vNodes)
foreach(CNode* pnode, vNodes)
if (pnode->IsSubscribed(nChannel))
return true;
return false;
}
bool CNode::IsSubscribed(unsigned int nChannel)
{
if (nChannel >= vfSubscribe.size())
return false;
return vfSubscribe[nChannel];
}
void CNode::Subscribe(unsigned int nChannel, unsigned int nHops)
{
if (nChannel >= vfSubscribe.size())
return;
if (!AnySubscribed(nChannel))
{
// Relay subscribe
CRITICAL_BLOCK(cs_vNodes)
foreach(CNode* pnode, vNodes)
if (pnode != this)
pnode->PushMessage("subscribe", nChannel, nHops);
}
vfSubscribe[nChannel] = true;
}
void CNode::CancelSubscribe(unsigned int nChannel)
{
if (nChannel >= vfSubscribe.size())
return;
// Prevent from relaying cancel if wasn't subscribed
if (!vfSubscribe[nChannel])
return;
vfSubscribe[nChannel] = false;
if (!AnySubscribed(nChannel))
{
// Relay subscription cancel
CRITICAL_BLOCK(cs_vNodes)
foreach(CNode* pnode, vNodes)
if (pnode != this)
pnode->PushMessage("sub-cancel", nChannel);
// Clear memory, no longer subscribed
if (nChannel == MSG_PRODUCT)
CRITICAL_BLOCK(cs_mapProducts)
mapProducts.clear();
}
}
CNode* FindNode(unsigned int ip)
{
CRITICAL_BLOCK(cs_vNodes)
{
foreach(CNode* pnode, vNodes)
if (pnode->addr.ip == ip)
return (pnode);
}
return NULL;
}
// Synthetic marker address for a tunneled `.btf` peer. The real endpoint is
// unknown by design (the tunnel hides it), so tag the CNode with a non-routable
// 10.x.x.x address (fails IsRoutable, so it is never gossiped as a real peer)
// that is stable per identity, keeping FindNode and the duplicate check working.
static CAddress BtfMarkerAddr(const unsigned char b5[5])
{
unsigned int ip;
unsigned char b[4] = { 10, b5[0], b5[1], b5[2] };
memcpy(&ip, b, 4);
unsigned short port = htons((unsigned short)((b5[3] << 8) | b5[4]));
return CAddress(ip, port, nLocalServices);
}
// Shared tail: given a peer's pubkey and already-resolved rendezvous
// coordinates, open the tunnel and register the CNode. Used by both
// ConnectNodeBtf (which resolves the descriptor itself) and
// ConnectNodeBtfResolved (which takes an already-resolved descriptor, so it
// makes no Nostr relay calls at all -- see nostr.cpp's BtfResolveMany for why
// that matters when dialing many candidates in parallel).
//
// Peers we have actually reached, remembered across restarts.
//
// Discovery is otherwise entirely dependent on the Nostr relays: a node that
// has been running for hours and knows exactly which peers answer throws all
// of it away on exit, and the next start walks the same ~96%-dead descriptor
// list again. Reconnecting from this file skips the relays completely --
// address, meeting node and encryption key are all we need.
//
static const size_t MAX_CACHED_BTF_PEERS = 50;
static const int64 CACHED_BTF_PEER_TTL = 7 * 24 * 60 * 60; // a week
struct CachedBtfPeer
{
string btfAddr;
string meeting;
string encHex;
int64 lastSeen;
};
static string BtfPeerCachePath() { return GetAppDir() + "/btfpeers.json"; }
static string BytesToHex(const unsigned char* p, size_t n)
{
static const char* h = "0123456789abcdef";
string s;
s.reserve(n * 2);
for (size_t i = 0; i < n; i++) { s += h[p[i] >> 4]; s += h[p[i] & 0xf]; }
return s;
}
static bool HexToBytes(const string& s, unsigned char* out, size_t n)
{
if (s.size() != n * 2) return false;
for (size_t i = 0; i < n; i++)
{
unsigned int b;
if (sscanf(s.c_str() + i * 2, "%2x", &b) != 1) return false;
out[i] = (unsigned char)b;
}
return true;
}
void LoadCachedBtfPeers(vector<CachedBtfPeer>& out)
{
out.clear();
FILE* f = fopen(BtfPeerCachePath().c_str(), "r");
if (!f) return;
string body;
char buf[4096];
size_t r;
while ((r = fread(buf, 1, sizeof(buf), f)) > 0) body.append(buf, r);
fclose(f);
try
{
nlohmann::json arr = nlohmann::json::parse(body);
if (!arr.is_array()) return;
int64 nNow = GetTime();
for (const auto& o : arr)
{
if (!o.is_object()) continue;
if (!o.contains("btf") || !o["btf"].is_string()) continue;
if (!o.contains("meeting") || !o["meeting"].is_string()) continue;
if (!o.contains("enc") || !o["enc"].is_string()) continue;
CachedBtfPeer p;
p.btfAddr = o["btf"].get<string>();
p.meeting = o["meeting"].get<string>();
p.encHex = o["enc"].get<string>();
p.lastSeen = o.value("seen", (int64)0);
if (nNow - p.lastSeen > CACHED_BTF_PEER_TTL) continue; // long gone
out.push_back(p);
}
}
catch (...)
{
LogPrint("net", "btfpeers: cache unreadable, starting empty\n");
out.clear();
}
}
static CCriticalSection cs_btfPeerCache;
static void RememberBtfPeer(const string& strBtfAddr, const string& strMeeting,
const unsigned char enc_pub[32])
{
CRITICAL_BLOCK(cs_btfPeerCache)
{
vector<CachedBtfPeer> peers;
LoadCachedBtfPeers(peers);
for (size_t i = 0; i < peers.size(); i++)
if (peers[i].btfAddr == strBtfAddr) { peers.erase(peers.begin() + i); break; }
CachedBtfPeer p;
p.btfAddr = strBtfAddr;
p.meeting = strMeeting;
p.encHex = BytesToHex(enc_pub, 32);
p.lastSeen = GetTime();
peers.insert(peers.begin(), p); // most recent first
if (peers.size() > MAX_CACHED_BTF_PEERS)
peers.resize(MAX_CACHED_BTF_PEERS);
nlohmann::json arr = nlohmann::json::array();
foreach(const CachedBtfPeer& q, peers)
{
nlohmann::json o;
o["btf"] = q.btfAddr;
o["meeting"] = q.meeting;
o["enc"] = q.encHex;
o["seen"] = q.lastSeen;
arr.push_back(o);
}
FILE* f = fopen(BtfPeerCachePath().c_str(), "w");
if (f)
{
string s = arr.dump(2);
fwrite(s.c_str(), 1, s.size(), f);
fclose(f);
}
}
}
// Dial everything we reached last time, before the relays have said anything.
void ThreadReconnectCachedBtfPeers(void* parg)
{
vector<CachedBtfPeer> peers;
LoadCachedBtfPeers(peers);
if (peers.empty())
{
LogPrint("net", "btfpeers: no cache yet, waiting on relay discovery\n");
return;
}
LogPrint("net", "btfpeers: trying %zu remembered peer(s) before discovery\n",
peers.size());
int nConnected = 0;
foreach(const CachedBtfPeer& p, peers)
{
if (fShutdown) return;
unsigned char enc[32];
if (!HexToBytes(p.encHex, enc, 32)) continue;
if (ConnectNodeBtfResolved(p.btfAddr, p.meeting, enc))
{
nConnected++;
if (nConnected >= 8) break; // enough to bootstrap; the rest can wait
}
}
LogPrint("net", "btfpeers: %d of %zu remembered peer(s) answered\n",
nConnected, peers.size());
}
static CNode* ConnectNodeBtfTail(const string& strBtfAddr, const unsigned char pk[32],
const string& strMeeting, const unsigned char enc_pub[32])
{
CAddress addr = BtfMarkerAddr(pk);
CNode* pnode = FindNode(addr.ip);
if (pnode)
{
pnode->AddRef();
return pnode;
}
size_t colon = strMeeting.rfind(':');
if (colon == string::npos)
return NULL;
string strHost = strMeeting.substr(0, colon);
int nPort = atoi(strMeeting.substr(colon + 1).c_str());
if (nPort <= 0 || nPort > 65535)
return NULL;
btf_socket_t hSocket = btf::BtfClientTunnel(strHost.c_str(), (unsigned short)nPort, pk, enc_pub);
if (hSocket == INVALID_SOCKET)
{
if (fDebug)
LogPrint("net", "ConnectNodeBtf: tunnel to %s via %s failed\n", strBtfAddr.c_str(), strMeeting.c_str());
return NULL;
}
if (fDebug)
LogPrint("net", "connected %s via rendezvous %s\n", strBtfAddr.c_str(), strMeeting.c_str());
// This one answered -- worth trying first next time we start.
RememberBtfPeer(strBtfAddr, strMeeting, enc_pub);
// Add node
pnode = new CNode(hSocket, addr, false);
pnode->AddRef();
CRITICAL_BLOCK(cs_vNodes)
vNodes.push_back(pnode);
return pnode;
}
// Connect to a peer by its `.btf` address: resolve the self-certified
// descriptor over Nostr, then tunnel through its meeting node with the
// end-to-end channel. Neither side ever learns the other's IP.
CNode* ConnectNodeBtf(const string& strBtfAddr)
{
unsigned char pk[32];
if (!btf::ParseAddress(strBtfAddr, pk))
{
LogPrint("net", "ConnectNodeBtf: invalid address %s\n", strBtfAddr.c_str());
return NULL;
}
if (BtfLocalAddress() == strBtfAddr)
return NULL; // ourselves
if (fDebug)
LogPrint("net", "trying %s\n", strBtfAddr.c_str());
string strMeeting;
unsigned char enc_pub[32];
if (!BtfResolve(strBtfAddr, strMeeting, enc_pub))
{
if (fDebug)
LogPrint("net", "ConnectNodeBtf: could not resolve a descriptor for %s\n", strBtfAddr.c_str());
return NULL;
}
return ConnectNodeBtfTail(strBtfAddr, pk, strMeeting, enc_pub);
}
// Same as ConnectNodeBtf, but skips the Nostr resolve step because the caller
// already resolved the descriptor (e.g. via BtfResolveMany, batching many
// addresses into one relay round-trip instead of one relay round-trip per
// address). Makes zero relay connections -- only talks to the peer's
// rendezvous meeting node.
CNode* ConnectNodeBtfResolved(const string& strBtfAddr, const string& strMeeting,
const unsigned char enc_pub[32])
{
unsigned char pk[32];
if (!btf::ParseAddress(strBtfAddr, pk))
{
LogPrint("net", "ConnectNodeBtf: invalid address %s\n", strBtfAddr.c_str());
return NULL;
}
if (BtfLocalAddress() == strBtfAddr)
return NULL; // ourselves
return ConnectNodeBtfTail(strBtfAddr, pk, strMeeting, enc_pub);
}
// Anonymous inbound listener (this node's `.btf` hidden service). Registers at
// the meeting relay and blocks until a client dials our address; each pairing
// becomes a normal inbound CNode riding the end-to-end channel, then we
// register again for the next caller.
void ThreadBtfAccept(void* parg)
{
printf("ThreadBtfAccept started\n");
unsigned char pk[32];
unsigned char sk[32];
while (!BtfGetIdentity(pk, sk))
{
if (fShutdown)
return;
Sleep(5000);
}
size_t iRelay = 0;
bool fPicked = false;
loop
{
if (fShutdown)
return;
// Curated seeds + relays discovered from Nostr announcements.
vector<string> relays = BtfAllRelays();
if (relays.empty())
{
Sleep(10000); // no meeting relay configured
continue;
}
// Random start spreads nodes across all relays (incl. volunteer ones).
if (!fPicked)
{
iRelay = (size_t)GetRand(relays.size());
fPicked = true;
}
// Stick to the current relay while it works; on failure, fail over to
// the next one so a DDoS'd/blocked relay IP can't keep us offline.
string strMeeting = relays[iRelay % relays.size()];
size_t colon = strMeeting.rfind(':');
if (colon == string::npos)
{
iRelay++;
Sleep(2000);
continue;
}
string strHost = strMeeting.substr(0, colon);
int nPort = atoi(strMeeting.substr(colon + 1).c_str());
// Blocks until a client is paired to us (or the relay drops us)
btf::RvSocket rv = btf::RvServiceRegister(strHost.c_str(), (unsigned short)nPort, pk);
if (fShutdown)
{
if (rv != btf::RV_INVALID)
btf::RvClose(rv);
return;
}
if (rv == btf::RV_INVALID)
{
iRelay++; // this relay is down/attacked -> try the next one
Sleep(3000);
continue;
}
// Registered OK: advertise THIS relay in our descriptor so clients dial
// us here, and keep using it (iRelay unchanged) until it fails.
BtfSetActiveRelay(strMeeting);
btf_socket_t hSocket = btf::BtfServiceWrap(rv, sk);
if (hSocket == INVALID_SOCKET)
continue;
// The dialer is anonymous (its pubkey never reaches us), so tag the
// connection with a random marker address.
unsigned char rnd[5];
RAND_bytes(rnd, sizeof(rnd));
CAddress addr = BtfMarkerAddr(rnd);
LogPrint("net", "accepted .btf connection via rendezvous %s\n", strMeeting.c_str());
CNode* pnode = new CNode(hSocket, addr, true);
pnode->AddRef();
CRITICAL_BLOCK(cs_vNodes)
vNodes.push_back(pnode);
}
}
// Keep an outbound connection to a specific `.btf` peer (from /connectbtf) --
// the rendezvous analogue of addnode. Retries until connected, reconnects if
// the tunnel drops.
void ThreadBtfConnect(void* parg)
{
printf("ThreadBtfConnect started\n");
string strAddr = *(string*)parg;
delete (string*)parg;
loop
{
if (fShutdown)
return;
try
{
CNode* pnode = ConnectNodeBtf(strAddr);
if (pnode)
{
if (!pnode->fNetworkNode)
pnode->fNetworkNode = true; // keep the ref from ConnectNodeBtf
else
pnode->Release(); // already pinned; drop the extra ref
}
}
CATCH_PRINT_EXCEPTION("ThreadBtfConnect")
for (int i = 0; i < 30 && !fShutdown; i++)
Sleep(1000);
}
}
void CNode::Disconnect()
{
LogPrint("net", "disconnecting node %s\n", addr.ToString().c_str());
closesocket(hSocket);
// All of a nodes broadcasts and subscriptions are automatically torn down
// when it goes down, so a node has to stay up to keep its broadcast going.
CRITICAL_BLOCK(cs_mapProducts)
for (map<uint256, CProduct>::iterator mi = mapProducts.begin(); mi != mapProducts.end();)
AdvertRemoveSource(this, MSG_PRODUCT, 0, (*(mi++)).second);
// Cancel subscriptions
for (unsigned int nChannel = 0; nChannel < vfSubscribe.size(); nChannel++)
if (vfSubscribe[nChannel])
CancelSubscribe(nChannel);
}
void ThreadSocketHandler(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadSocketHandler(parg));
loop
{
vfThreadRunning[0] = true;
CheckForShutdown(0);
try
{
ThreadSocketHandler2(parg);
}
CATCH_PRINT_EXCEPTION("ThreadSocketHandler()")
vfThreadRunning[0] = false;
Sleep(5000);
}
}
void ThreadSocketHandler2(void* parg)
{
printf("ThreadSocketHandler started\n");
SOCKET hListenSocket = *(SOCKET*)parg;
list<CNode*> vNodesDisconnected;
int nPrevNodeCount = 0;
loop
{
//
// Disconnect nodes
//
CRITICAL_BLOCK(cs_vNodes)
{
// Disconnect duplicate connections
map<unsigned int, CNode*> mapFirst;
foreach(CNode* pnode, vNodes)
{
if (pnode->fDisconnect)
continue;
unsigned int ip = pnode->addr.ip;
if (mapFirst.count(ip) && addrLocalHost.ip < ip)
{
// In case two nodes connect to each other at once,
// the lower ip disconnects its outbound connection
CNode* pnodeExtra = mapFirst[ip];
if (pnodeExtra->GetRefCount() > (pnodeExtra->fNetworkNode ? 1 : 0))
swap(pnodeExtra, pnode);
if (pnodeExtra->GetRefCount() <= (pnodeExtra->fNetworkNode ? 1 : 0))
{
LogPrint("net", "(%d nodes) disconnecting duplicate: %s\n", vNodes.size(), pnodeExtra->addr.ToString().c_str());
if (pnodeExtra->fNetworkNode && !pnode->fNetworkNode)
{
pnode->AddRef();
swap(pnodeExtra->fNetworkNode, pnode->fNetworkNode);
pnodeExtra->Release();
}
pnodeExtra->fDisconnect = true;
}
}
mapFirst[ip] = pnode;
}
// Disconnect unused nodes
vector<CNode*> vNodesCopy = vNodes;
foreach(CNode* pnode, vNodesCopy)
{
if (pnode->ReadyToDisconnect() && pnode->vRecv.empty() && pnode->vSend.empty())
{
// remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
pnode->Disconnect();
// hold in disconnected pool until all refs are released
pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 5 * 60);
if (pnode->fNetworkNode)
pnode->Release();
vNodesDisconnected.push_back(pnode);
}
}
// Delete disconnected nodes
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
foreach(CNode* pnode, vNodesDisconnectedCopy)
{
// wait until threads are done using it
if (pnode->GetRefCount() <= 0)
{
bool fDelete = false;
TRY_CRITICAL_BLOCK(pnode->cs_vSend)
TRY_CRITICAL_BLOCK(pnode->cs_vRecv)
TRY_CRITICAL_BLOCK(pnode->cs_mapRequests)
TRY_CRITICAL_BLOCK(pnode->cs_inventory)
fDelete = true;
if (fDelete)
{
vNodesDisconnected.remove(pnode);
delete pnode;
}
}
}
}
if (vNodes.size() != nPrevNodeCount)
{
nPrevNodeCount = vNodes.size();
MainFrameRepaint();
}
//
// Find which sockets have data to receive
//
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50000; // frequency to poll pnode->vSend
fd_set fdsetRecv;
fd_set fdsetSend;
FD_ZERO(&fdsetRecv);
FD_ZERO(&fdsetSend);
SOCKET hSocketMax = 0;
FD_SET(hListenSocket, &fdsetRecv);
hSocketMax = max(hSocketMax, hListenSocket);
CRITICAL_BLOCK(cs_vNodes)
{
foreach(CNode* pnode, vNodes)
{
FD_SET(pnode->hSocket, &fdsetRecv);
hSocketMax = max(hSocketMax, pnode->hSocket);
TRY_CRITICAL_BLOCK(pnode->cs_vSend)
if (!pnode->vSend.empty())
FD_SET(pnode->hSocket, &fdsetSend);
}
}
vfThreadRunning[0] = false;
int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, NULL, &timeout);
vfThreadRunning[0] = true;
CheckForShutdown(0);
if (nSelect == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
LogPrint("net", "select failed: %d\n", nErr);
for (int i = 0; i <= hSocketMax; i++)
{
FD_SET(i, &fdsetRecv);
FD_SET(i, &fdsetSend);
}
Sleep(timeout.tv_usec/1000);
}
RandAddSeed();
//// debug print
//foreach(CNode* pnode, vNodes)
//{
// printf("vRecv = %-5d ", pnode->vRecv.size());
// printf("vSend = %-5d ", pnode->vSend.size());
//}
//printf("\n");
//
// Accept new connections
//
if (FD_ISSET(hListenSocket, &fdsetRecv))
{
struct sockaddr_in sockaddr;
#ifdef _WIN32
int len = sizeof(sockaddr);
#else
socklen_t len = sizeof(sockaddr);
#endif
SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
CAddress addr(sockaddr);
if (hSocket == INVALID_SOCKET)
{
if (WSAGetLastError() != WSAEWOULDBLOCK)
printf("ERROR ThreadSocketHandler accept failed: %d\n", WSAGetLastError());
}
else
{
LogPrint("net", "accepted connection from %s\n", addr.ToString().c_str());
CNode* pnode = new CNode(hSocket, addr, true);
pnode->AddRef();
CRITICAL_BLOCK(cs_vNodes)
vNodes.push_back(pnode);
}
}
//
// Service each socket
//
vector<CNode*> vNodesCopy;
CRITICAL_BLOCK(cs_vNodes)
vNodesCopy = vNodes;
foreach(CNode* pnode, vNodesCopy)
{
CheckForShutdown(0);
SOCKET hSocket = pnode->hSocket;
//
// Receive
//
if (FD_ISSET(hSocket, &fdsetRecv))
{
TRY_CRITICAL_BLOCK(pnode->cs_vRecv)
{
CDataStream& vRecv = pnode->vRecv;
unsigned int nPos = vRecv.size();
// typical socket buffer is 8K-64K
const unsigned int nBufSize = 0x10000;
vRecv.resize(nPos + nBufSize);
int nBytes = recv(hSocket, &vRecv[nPos], nBufSize, 0);
vRecv.resize(nPos + max(nBytes, 0));
if (nBytes == 0)
{
// socket closed gracefully
if (!pnode->fDisconnect)
LogPrint("net", "recv: socket closed\n");
pnode->fDisconnect = true;
}
else if (nBytes < 0)
{
// socket error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
if (!pnode->fDisconnect)
LogPrint("net", "recv failed: %d\n", nErr);
pnode->fDisconnect = true;
}
}
}
}
//
// Send
//
if (FD_ISSET(hSocket, &fdsetSend))
{
TRY_CRITICAL_BLOCK(pnode->cs_vSend)
{
CDataStream& vSend = pnode->vSend;
if (!vSend.empty())
{
int nBytes = send(hSocket, &vSend[0], vSend.size(), 0);
if (nBytes > 0)
{
vSend.erase(vSend.begin(), vSend.begin() + nBytes);
}
else if (nBytes == 0)
{
if (pnode->ReadyToDisconnect())
pnode->vSend.clear();
}
else
{
LogPrint("net", "send error %d\n", nBytes);
if (pnode->ReadyToDisconnect())
pnode->vSend.clear();
}
}
}
}
}
Sleep(10);
}
}
void ThreadMessageHandler(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadMessageHandler(parg));
loop
{
vfThreadRunning[2] = true;
CheckForShutdown(2);
try
{
ThreadMessageHandler2(parg);
}
CATCH_PRINT_EXCEPTION("ThreadMessageHandler()")
vfThreadRunning[2] = false;
Sleep(5000);
}
}
void ThreadMessageHandler2(void* parg)
{
printf("ThreadMessageHandler started\n");
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
loop
{
// Poll the connected nodes for messages
vector<CNode*> vNodesCopy;
CRITICAL_BLOCK(cs_vNodes)
vNodesCopy = vNodes;
foreach(CNode* pnode, vNodesCopy)
{
pnode->AddRef();
// Receive messages
TRY_CRITICAL_BLOCK(pnode->cs_vRecv)
ProcessMessages(pnode);
// Send messages
TRY_CRITICAL_BLOCK(pnode->cs_vSend)
SendMessages(pnode);
pnode->Release();
}
// Wait and allow messages to bunch up
vfThreadRunning[2] = false;
Sleep(100);
vfThreadRunning[2] = true;
CheckForShutdown(2);
}
}
//// todo: start one thread per processor, use getenv("NUMBER_OF_PROCESSORS")
void ThreadBitcoinMiner(void* parg)
{
vfThreadRunning[3] = true;
CheckForShutdown(3);
try
{
bool fRet = BitcoinMiner();
printf("BitcoinMiner returned %s\n\n\n", fRet ? "true" : "false");
}
CATCH_PRINT_EXCEPTION("BitcoinMiner()")
vfThreadRunning[3] = false;
}
bool StartNode(string& strError)
{
strError = "";
// Sockets startup
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR)
{
strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
printf("%s\n", strError.c_str());
return false;
}
// Get local host ip
char pszHostName[255];
if (gethostname(pszHostName, 255) == SOCKET_ERROR)
{
strError = strprintf("Error: Unable to get IP address of this computer (gethostname returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
struct hostent* pHostEnt = gethostbyname(pszHostName);
if (!pHostEnt)
{
strError = strprintf("Error: Unable to get IP address of this computer (gethostbyname returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
addrLocalHost = CAddress(*(long*)(pHostEnt->h_addr_list[0]),
nListenPort,
nLocalServices);
printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str());
// Create socket for listening for incoming connections
SOCKET hListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET)
{
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
// Set to nonblocking, incoming connections will also inherit this
u_long nOne = 1;
if (ioctlsocket(hListenSocket, FIONBIO, &nOne) == SOCKET_ERROR)
{
strError = strprintf("Error: Couldn't set properties on socket for incoming connections (ioctlsocket returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
// The sockaddr_in structure specifies the address family,
// IP address, and port for the socket that is being bound
int nRetryLimit = 15;
struct sockaddr_in sockaddr = addrLocalHost.GetSockAddr();
if (bind(hListenSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf("Error: Unable to bind to port %s on this computer. The program is probably already running.", addrLocalHost.ToString().c_str());
else
strError = strprintf("Error: Unable to bind to port %s on this computer (bind returned error %d)", addrLocalHost.ToString().c_str(), nErr);
printf("%s\n", strError.c_str());
return false;
}
printf("bound to addrLocalHost = %s\n\n", addrLocalHost.ToString().c_str());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
// Get our external IP in a background thread -- up to 4 HTTP requests with
// 5s timeouts each could otherwise delay startup by 20s on first run.
// addrIncoming from a previous session is used immediately as a fallback.
if (addrIncoming.ip)
addrLocalHost.ip = addrIncoming.ip;
_beginthread([](void*) {
unsigned int ip = addrLocalHost.ip;
if (GetMyExternalIP(ip)) {
addrLocalHost.ip = ip;
addrIncoming = addrLocalHost;
CWalletDB().WriteSetting("addrIncoming", addrIncoming);
printf("External IP updated: %s\n", addrLocalHost.ToStringIP().c_str());
}
}, 0, NULL);
// Peers that answered last time, dialled straight away. The relays are the
// only way to find anyone otherwise, and reaching them plus walking their
// descriptor list is what makes a restart take minutes.
if (_beginthread(ThreadReconnectCachedBtfPeers, 0, NULL) == -1)
printf("Error: _beginthread(ThreadReconnectCachedBtfPeers) failed\n");
// Peer discovery over Nostr relays (replaces the old IRC seed)
if (_beginthread(ThreadNostrSeed, 0, NULL) == -1)
printf("Error: _beginthread(ThreadNostrSeed) failed\n");
// Anonymous inbound: this node's .btf hidden service, reachable through the
// meeting relay without exposing our IP or needing a public port.
if (!vBtfMeetingRelays.empty())
if (_beginthread(ThreadBtfAccept, 0, NULL) == -1)
printf("Error: _beginthread(ThreadBtfAccept) failed\n");
// Anonymous outbound: keep a connection to a specific .btf peer, if asked.
if (!strBtfConnect.empty())
if (_beginthread(ThreadBtfConnect, 0, new string(strBtfConnect)) == -1)
printf("Error: _beginthread(ThreadBtfConnect) failed\n");
//
// Start threads
//
if (_beginthread(ThreadSocketHandler, 0, new SOCKET(hListenSocket)) == -1)
{
strError = "Error: _beginthread(ThreadSocketHandler) failed";
printf("%s\n", strError.c_str());
return false;
}
if (_beginthread(ThreadMessageHandler, 0, NULL) == -1)
{
strError = "Error: _beginthread(ThreadMessageHandler) failed";
printf("%s\n", strError.c_str());
return false;
}
return true;
}
bool StopNode()
{
printf("StopNode()\n");
fShutdown = true;
nTransactionsUpdated++;
while (count(vfThreadRunning.begin(), vfThreadRunning.end(), true))
Sleep(10);
Sleep(50);
// Sockets shutdown
WSACleanup();
return true;
}
void CheckForShutdown(int n)
{
if (fShutdown)
{
if (n != -1)
vfThreadRunning[n] = false;
_endthread();
}
}
|