upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/Makefile4
-rw-r--r--src/btfrv.cpp49
-rw-r--r--src/btftunnel.cpp103
-rw-r--r--src/gui.cpp34
-rw-r--r--src/main.cpp98
-rw-r--r--src/net.cpp5
-rw-r--r--src/nostr.cpp25
-rw-r--r--src/nostr.h3
-rw-r--r--src/randomx_pow.cpp28
-rw-r--r--src/rpc.cpp76
-rw-r--r--src/util.h2
11 files changed, 388 insertions, 39 deletions
diff --git a/src/Makefile b/src/Makefile
index 1bc3ae8..2c6d304 100644
--- a/src/Makefile
+++ b/src/Makefile
@@ -6,7 +6,9 @@ FUZZ_CXX ?= clang++
6 6
7SECP_INC ?= /usr/local/include 7SECP_INC ?= /usr/local/include
8SECP_LIB ?= /usr/local/lib 8SECP_LIB ?= /usr/local/lib
9RANDOMX_DIR ?= $(HOME)/RandomX 9# The root Makefile exports RANDOMX_DIR (default: <repo>/randomx-build, built
10# by deps-randomx). This fallback only applies when src/ is built standalone.
11RANDOMX_DIR ?= $(abspath $(CURDIR)/..)/randomx-build
10 12
11IMGUI_DIR = imgui 13IMGUI_DIR = imgui
12 14
diff --git a/src/btfrv.cpp b/src/btfrv.cpp
index 133eb89..8ab735c 100644
--- a/src/btfrv.cpp
+++ b/src/btfrv.cpp
@@ -40,6 +40,8 @@ typedef int SOCKET;
40#include <thread> 40#include <thread>
41#include <mutex> 41#include <mutex>
42#include <atomic> 42#include <atomic>
43#include <chrono>
44#include <system_error>
43 45
44namespace btf 46namespace btf
45{ 47{
@@ -209,8 +211,28 @@ static void HandleIncoming(SOCKET s)
209 bool a = WriteN(svc, &ok, 1); 211 bool a = WriteN(svc, &ok, 1);
210 bool b = WriteN(s, &ok, 1); 212 bool b = WriteN(s, &ok, 1);
211 if (!a || !b) { CLOSESOCK(svc); CLOSESOCK(s); return; } 213 if (!a || !b) { CLOSESOCK(svc); CLOSESOCK(s); return; }
212 std::thread(Forward, s, svc).detach(); 214 // One thread pumps s -> svc; this thread pumps svc -> s. Spawning a
213 std::thread(Forward, svc, s).detach(); 215 // thread per direction left no clean way to fail the second spawn:
216 // std::thread throws std::system_error when pthread_create is refused
217 // (NPROC limit, container pids cgroup, memory pressure), the first
218 // pump was already detached, and closing its sockets from here would
219 // race it -- so nothing caught the throw and it reached
220 // std::terminate, killing the relay over one pair it could not serve.
221 // Running one direction on this thread leaves exactly one spawn to
222 // guard, and a failure here has nothing running yet to race.
223 try
224 {
225 std::thread(Forward, s, svc).detach();
226 }
227 catch (const std::system_error& e)
228 {
229 fprintf(stderr, "rendezvous relay: cannot spawn forward thread (%s), pair dropped\n",
230 e.what());
231 CLOSESOCK(svc);
232 CLOSESOCK(s);
233 return;
234 }
235 Forward(svc, s);
214 } 236 }
215 else 237 else
216 { 238 {
@@ -236,6 +258,7 @@ bool RvRelayRun(unsigned short port)
236 if (bind(g_listen, (struct sockaddr*)&addr, sizeof(addr)) != 0) { CLOSESOCK(g_listen); return false; } 258 if (bind(g_listen, (struct sockaddr*)&addr, sizeof(addr)) != 0) { CLOSESOCK(g_listen); return false; }
237 if (listen(g_listen, 16) != 0) { CLOSESOCK(g_listen); return false; } 259 if (listen(g_listen, 16) != 0) { CLOSESOCK(g_listen); return false; }
238 260
261 int nSpawnFails = 0;
239 while (!g_stop) 262 while (!g_stop)
240 { 263 {
241 struct sockaddr_in cli; 264 struct sockaddr_in cli;
@@ -246,7 +269,27 @@ bool RvRelayRun(unsigned short port)
246 if (g_stop) break; 269 if (g_stop) break;
247 continue; 270 continue;
248 } 271 }
249 std::thread(HandleIncoming, s).detach(); 272 try
273 {
274 std::thread(HandleIncoming, s).detach();
275 nSpawnFails = 0;
276 }
277 catch (const std::system_error& e)
278 {
279 // A refused pthread_create is backpressure, not a reason to die:
280 // the condition behind it (NPROC, pids cgroup, memory) does not
281 // clear in milliseconds, and the connection count feeding it is
282 // attacker-influenced. Drop this one peer, stop accepting for a
283 // moment -- longer each time, capped -- and keep serving the
284 // connections already established.
285 fprintf(stderr, "rendezvous relay: cannot spawn connection thread (%s), connection dropped\n",
286 e.what());
287 CLOSESOCK(s);
288 nSpawnFails++;
289 int nWaitMs = nSpawnFails < 5 ? nSpawnFails * 1000 : 5000;
290 for (int i = 0; i < nWaitMs && !g_stop; i += 100)
291 std::this_thread::sleep_for(std::chrono::milliseconds(100));
292 }
250 } 293 }
251 CLOSESOCK(g_listen); 294 CLOSESOCK(g_listen);
252 g_listen = INVALID_SOCKET; 295 g_listen = INVALID_SOCKET;
diff --git a/src/btftunnel.cpp b/src/btftunnel.cpp
index 63d178b..4acca1a 100644
--- a/src/btftunnel.cpp
+++ b/src/btftunnel.cpp
@@ -25,8 +25,12 @@ typedef int SOCKET;
25#endif 25#endif
26#include "sockcount.h" 26#include "sockcount.h"
27#include <cstring> 27#include <cstring>
28#include <cstdio>
29#include <memory>
30#include <new>
28#include <vector> 31#include <vector>
29#include <thread> 32#include <thread>
33#include <system_error>
30 34
31namespace btf 35namespace btf
32{ 36{
@@ -119,20 +123,111 @@ static void PumpIn(SOCKET pumpEnd, RvSocket rv, std::vector<unsigned char> key)
119 shutdown((SOCKET)rv, SD_BOTH); 123 shutdown((SOCKET)rv, SD_BOTH);
120} 124}
121 125
126// The pump end and the rendezvous socket, owned jointly by whoever is still
127// using them. Closed once, by the last reference to go.
128//
129// Joint ownership rather than "the inbound pump owns the cleanup", because
130// either pump can reach its exit first and BOTH touch BOTH descriptors on the
131// way out -- PumpOut ends in shutdown(rv), shutdown(pumpEnd) and PumpIn ends in
132// the mirror image. A single owner therefore has no exit at which the other is
133// guaranteed to be finished. Holding a reference for the whole body of each
134// pump gives it one: the close cannot happen until the last pump has stopped
135// touching the descriptors, so no shutdown() can land on a number that has
136// already been closed and handed back out by the kernel to an unrelated
137// connection.
138struct TunnelEnds
139{
140 SOCKET pumpEnd;
141 RvSocket rv;
142 TunnelEnds(SOCKET p, RvSocket r) : pumpEnd(p), rv(r) {}
143 ~TunnelEnds() { BtfCloseSocket(pumpEnd); RvClose(rv); }
144private:
145 TunnelEnds(const TunnelEnds&);
146 TunnelEnds& operator=(const TunnelEnds&);
147};
148
122// Start the two pumps and hand back the app-facing socket. When both pumps 149// Start the two pumps and hand back the app-facing socket. When both pumps
123// finish, close the pump end and the rendezvous socket. 150// finish, close the pump end and the rendezvous socket.
151//
152// That sentence used to be a comment describing something the code did not do.
153// The inbound pump closed both descriptors as soon as it exited, without
154// waiting for the outbound pump, which then called shutdown() on both at its
155// own exit. Whether that shutdown hit a live descriptor or a closed one came
156// down to which pump got there first, and the rendezvous socket dying before
157// the app socket -- a relay restart, the far side hanging up -- is precisely
158// the order that puts the inbound pump ahead. Measured over 25 such teardowns
159// against the real code: 29 shutdowns landed on an already-closed descriptor.
160//
161// appEnd is not part of this. It is handed to the caller on success and closed
162// here on every failure path; no pump ever touches it.
163//
164// Every tunnel is two threads, and a tunnel is one peer connection (a .btf
165// dial or accept, a pool miner, a participant's pool session) -- so the
166// thread count scales with peer count, which is attacker-influenced. When
167// pthread_create is refused std::thread throws std::system_error; uncaught it
168// reached std::terminate and took the whole process down over one connection
169// it could not serve. Both spawns are guarded, and the failure paths return
170// INVALID_SOCKET, which every caller already handles by dropping just that
171// connection.
124static btf_socket_t StartTunnel(RvSocket rv, const unsigned char shared[32]) 172static btf_socket_t StartTunnel(RvSocket rv, const unsigned char shared[32])
125{ 173{
126 btf_socket_t appEnd, pumpEnd; 174 btf_socket_t appEnd, pumpEnd;
127 if (!MakeLocalPair(appEnd, pumpEnd)) { RvClose(rv); return INVALID_SOCKET; } 175 if (!MakeLocalPair(appEnd, pumpEnd)) { RvClose(rv); return INVALID_SOCKET; }
128 176
129 std::vector<unsigned char> key(shared, shared + 32); 177 std::vector<unsigned char> key(shared, shared + 32);
130 std::thread(PumpOut, pumpEnd, rv, key).detach(); 178
131 std::thread([pumpEnd, rv, key]() { 179 // make_shared, not shared_ptr(new ...): it allocates before it constructs,
132 PumpIn(pumpEnd, rv, key); 180 // so it either comes back owning both descriptors or throws having taken
181 // ownership of neither. The two-step form can run the deleter and then
182 // throw, which would close both here and again below.
183 std::shared_ptr<TunnelEnds> ends;
184 try
185 {
186 ends = std::make_shared<TunnelEnds>(pumpEnd, rv);
187 }
188 catch (const std::bad_alloc&)
189 {
190 fprintf(stderr, "btf tunnel: out of memory starting tunnel, tunnel dropped\n");
133 BtfCloseSocket(pumpEnd); 191 BtfCloseSocket(pumpEnd);
192 BtfCloseSocket(appEnd);
134 RvClose(rv); 193 RvClose(rv);
135 }).detach(); 194 return INVALID_SOCKET;
195 }
196
197 try
198 {
199 std::thread([ends, key]() { PumpIn(ends->pumpEnd, ends->rv, key); }).detach();
200 }
201 catch (const std::system_error& e)
202 {
203 // Nothing is running yet: `ends` is the only reference, and returning
204 // drops it, which is what closes pumpEnd and rv.
205 fprintf(stderr, "btf tunnel: cannot spawn inbound pump (%s), tunnel dropped\n",
206 e.what());
207 BtfCloseSocket(appEnd);
208 return INVALID_SOCKET;
209 }
210
211 try
212 {
213 std::thread([ends, key]() { PumpOut(ends->pumpEnd, ends->rv, key); }).detach();
214 }
215 catch (const std::system_error& e)
216 {
217 // The inbound pump may be parked in RvReadN(rv) or may already have
218 // exited -- when the spawn is refused because the process is loaded,
219 // the rendezvous socket is often dead for the same reason, and then
220 // PumpIn returns on its first length read. Either way this thread
221 // still holds a reference, so both descriptors are still open: the
222 // shutdown wakes the pump if it is parked and is harmless if it is
223 // not. The close belongs to whichever reference goes last.
224 fprintf(stderr, "btf tunnel: cannot spawn outbound pump (%s), tunnel dropped\n",
225 e.what());
226 shutdown((SOCKET)ends->rv, SD_BOTH);
227 shutdown(ends->pumpEnd, SD_BOTH);
228 BtfCloseSocket(appEnd);
229 return INVALID_SOCKET;
230 }
136 return appEnd; 231 return appEnd;
137} 232}
138 233
diff --git a/src/gui.cpp b/src/gui.cpp
index 8dcb854..9b3802b 100644
--- a/src/gui.cpp
+++ b/src/gui.cpp
@@ -15,6 +15,7 @@
15#include <atomic> 15#include <atomic>
16#include <mutex> 16#include <mutex>
17#include <thread> 17#include <thread>
18#include <system_error>
18#include "bip32.h" 19#include "bip32.h"
19#include "walletcmd.h" 20#include "walletcmd.h"
20#include "font_roboto.h" 21#include "font_roboto.h"
@@ -910,8 +911,16 @@ static void DrawOptionsDialog()
910 911
911 if (nMineMode == MINE_OPERATOR) { 912 if (nMineMode == MINE_OPERATOR) {
912 if (!gPoolServerRunning) { 913 if (!gPoolServerRunning) {
913 gPoolServerRunning = true; 914 // Claim the server is up only once it is. The flag used to
914 _beginthread(ThreadRPCServer, 0, NULL); 915 // be set first and the result never looked at, so a refused
916 // spawn left an operator with a pool that reports itself
917 // running, no RPC server for miners to reach, and nothing
918 // anywhere saying why. The flag also latches: with it set,
919 // this branch is never retried.
920 if (_beginthread(ThreadRPCServer, 0, NULL) == (uintptr_t)-1)
921 printf("Error: _beginthread(ThreadRPCServer) failed -- pool server not started\n");
922 else
923 gPoolServerRunning = true;
915 } else if (!gPoolRunning) { 924 } else if (!gPoolRunning) {
916 gPoolRunning = true; 925 gPoolRunning = true;
917 } 926 }
@@ -1124,11 +1133,28 @@ static void DrawRestorePhraseDialog()
1124 } 1133 }
1125 g_restoreDerived.store(0); 1134 g_restoreDerived.store(0);
1126 g_restoreRecovered.store(0); 1135 g_restoreRecovered.store(0);
1136 // Set before the spawn, not after: RestoreThread clears this
1137 // flag itself when it finishes, and a short restore can beat
1138 // us back here and have its `false` overwritten, leaving the
1139 // dialog disabled forever.
1127 g_restoreRunning.store(true); 1140 g_restoreRunning.store(true);
1128 // On its own thread: a restore walks the whole chain once per 1141 // On its own thread: a restore walks the whole chain once per
1129 // batch and would otherwise freeze the window for as long as it 1142 // batch and would otherwise freeze the window for as long as it
1130 // takes. 1143 // takes. A refused spawn is one restore that does not happen,
1131 std::thread(RestoreThread, std::string(g_restoreInput)).detach(); 1144 // not a reason to take the window down with an uncaught
1145 // std::system_error -- and the flag has to come back off, or
1146 // the dialog sits greyed out reporting a search nobody is
1147 // running.
1148 try
1149 {
1150 std::thread(RestoreThread, std::string(g_restoreInput)).detach();
1151 }
1152 catch (const std::system_error& e)
1153 {
1154 g_restoreRunning.store(false);
1155 std::lock_guard<std::mutex> lock(g_restoreResultMutex);
1156 g_restoreResult = std::string("Could not start the search: ") + e.what();
1157 }
1132 } 1158 }
1133 } 1159 }
1134 if (fBusy) 1160 if (fBusy)
diff --git a/src/main.cpp b/src/main.cpp
index 80f5f31..981509c 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -14,6 +14,7 @@
14#include <atomic> 14#include <atomic>
15#include <mutex> 15#include <mutex>
16#include <thread> 16#include <thread>
17#include <system_error>
17#include "bip32.h" 18#include "bip32.h"
18#include "btfaddr.h" 19#include "btfaddr.h"
19#include "btftunnel.h" 20#include "btftunnel.h"
@@ -3899,9 +3900,32 @@ connected:
3899 std::vector<ParticipantShareHit> shareHits; 3900 std::vector<ParticipantShareHit> shareHits;
3900 std::mutex shareHitsMtx; 3901 std::mutex shareHitsMtx;
3901 std::vector<std::thread> hashThreads; 3902 std::vector<std::thread> hashThreads;
3902 for (int i = 0; i < nWorkers; i++) 3903 try
3903 hashThreads.emplace_back(ParticipantHashWorker, &jobShared, i, nWorkers, 3904 {
3904 &shareHits, &shareHitsMtx); 3905 for (int i = 0; i < nWorkers; i++)
3906 hashThreads.emplace_back(ParticipantHashWorker, &jobShared, i, nWorkers,
3907 &shareHits, &shareHitsMtx);
3908 }
3909 catch (const std::system_error& e)
3910 {
3911 // A refused pthread_create used to reach std::terminate here and
3912 // kill the worker mid-session -- observed twice on an otherwise
3913 // healthy participant. Stop the workers that did start the same way
3914 // the disconnect path below does, drop this pool connection, and let
3915 // the caller's reconnect loop try again once the pressure clears.
3916 LogPrint("worker", "[worker] cannot spawn hash threads (%s)"
3917 " -- dropping pool connection\n", e.what());
3918 SetParticipantMiningStatus("hash thread spawn failed");
3919 {
3920 std::lock_guard<std::mutex> lk(jobShared.mtx);
3921 jobShared.stop = true;
3922 jobShared.haveJob = false;
3923 }
3924 for (std::thread& t : hashThreads)
3925 t.join();
3926 closesocket(s);
3927 return false;
3928 }
3905 LogPrint("worker", "[worker] spawned %d hash threads on shared RandomX dataset\n", 3929 LogPrint("worker", "[worker] spawned %d hash threads on shared RandomX dataset\n",
3906 nWorkers); 3930 nWorkers);
3907 const uint64 sessionStartHashes = gParticipantHashes.load(); 3931 const uint64 sessionStartHashes = gParticipantHashes.load();
@@ -3912,6 +3936,14 @@ connected:
3912 std::string jobId; 3936 std::string jobId;
3913 unsigned char header[80] = {}; 3937 unsigned char header[80] = {};
3914 uint256 target; 3938 uint256 target;
3939 // Cached answer to "which block is this job built on", for the
3940 // mining.notify handler below -- see the comment there. Session-local, so
3941 // a reconnect re-resolves rather than trusting an answer obtained before
3942 // a possible change of pool.
3943 uint256 hashPrevResolved; // prevhash the cached answer describes
3944 bool fPrevResolved = false; // whether that answer exists yet
3945 int nPrevHeight = -1; // its height, or -1 == unknown to us
3946 int nBestHeightResolved = -1; // nBestHeight when we last resolved
3915 double currentDifficulty = 1.0; // updated by mining.set_difficulty from pool 3947 double currentDifficulty = 1.0; // updated by mining.set_difficulty from pool
3916 bool haveJob = false; 3948 bool haveJob = false;
3917 bool gotSubscribeAck = false; 3949 bool gotSubscribeAck = false;
@@ -4040,8 +4072,64 @@ connected:
4040 jobShared.jobSeq++; 4072 jobShared.jobSeq++;
4041 jobShared.haveJob = true; 4073 jobShared.haveJob = true;
4042 } 4074 }
4043 LogPrint("worker", "[pool->worker] new job %s received\n", 4075 // Log the chain position the pool is
4044 jobId.c_str()); 4076 // building on, so a stale or private
4077 // fork is auditable from worker logs.
4078 // The prevhash comes from the header we
4079 // actually hash (== p[2] of the notify);
4080 // a brief cs_main lookup is safe here --
4081 // this thread holds no other lock.
4082 //
4083 // Resolving it is the expensive half, and
4084 // this is the socket-reading thread: block
4085 // validation can hold cs_main for a long
4086 // time, and every moment spent waiting on
4087 // it here is a moment set_difficulty and
4088 // share responses are not being handled.
4089 // Most notifies in a round are a new job
4090 // on the SAME tip, so the answer is cached
4091 // and re-resolved only when it could come
4092 // out differently: a prevhash we have not
4093 // resolved, or one we could NOT resolve
4094 // last time while the chain has since
4095 // moved (unknown -> known). A block's
4096 // height is fixed once mapBlockIndex knows
4097 // it, so a cached "known" never goes
4098 // stale. nBestHeight is read unlocked on
4099 // purpose -- it only decides whether to
4100 // repeat a lookup, never what gets
4101 // printed, so a stale read costs at most
4102 // one deferred or one extra lookup.
4103 // The line still prints in full for every
4104 // job, cached or not.
4105 uint256 hashPrev;
4106 memcpy(&hashPrev, header + 4, 32);
4107 if (LogAcceptsCategory("worker"))
4108 {
4109 int nBestHeightNow = nBestHeight;
4110 if (!fPrevResolved
4111 || hashPrev != hashPrevResolved
4112 || (nPrevHeight < 0 && nBestHeightNow != nBestHeightResolved))
4113 {
4114 nPrevHeight = -1;
4115 CRITICAL_BLOCK(cs_main)
4116 {
4117 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrev);
4118 if (mi != mapBlockIndex.end())
4119 nPrevHeight = (*mi).second->nHeight;
4120 }
4121 hashPrevResolved = hashPrev;
4122 nBestHeightResolved = nBestHeightNow;
4123 fPrevResolved = true;
4124 }
4125 if (nPrevHeight >= 0)
4126 LogPrint("worker", "[pool->worker] new job %s received, prevhash %s (known, job height %d)\n",
4127 jobId.c_str(), hashPrev.GetHex().c_str(),
4128 nPrevHeight + 1);
4129 else
4130 LogPrint("worker", "[pool->worker] new job %s received, prevhash %s (unknown to our chain)\n",
4131 jobId.c_str(), hashPrev.GetHex().c_str());
4132 }
4045 SetParticipantMiningStatus("hashing job " + jobId); 4133 SetParticipantMiningStatus("hashing job " + jobId);
4046 } 4134 }
4047 } 4135 }
diff --git a/src/net.cpp b/src/net.cpp
index fed6123..16038c8 100644
--- a/src/net.cpp
+++ b/src/net.cpp
@@ -2090,7 +2090,7 @@ bool StartNode(string& strError)
2090 if (addrIncoming.ip) 2090 if (addrIncoming.ip)
2091 addrLocalHost.ip = addrIncoming.ip; 2091 addrLocalHost.ip = addrIncoming.ip;
2092 2092
2093 _beginthread([](void*) { 2093 if (_beginthread([](void*) {
2094 unsigned int ip = addrLocalHost.ip; 2094 unsigned int ip = addrLocalHost.ip;
2095 if (GetMyExternalIP(ip)) { 2095 if (GetMyExternalIP(ip)) {
2096 addrLocalHost.ip = ip; 2096 addrLocalHost.ip = ip;
@@ -2098,7 +2098,8 @@ bool StartNode(string& strError)
2098 CWalletDB().WriteSetting("addrIncoming", addrIncoming); 2098 CWalletDB().WriteSetting("addrIncoming", addrIncoming);
2099 printf("External IP updated: %s\n", addrLocalHost.ToStringIP().c_str()); 2099 printf("External IP updated: %s\n", addrLocalHost.ToStringIP().c_str());
2100 } 2100 }
2101 }, 0, NULL); 2101 }, 0, NULL) == (uintptr_t)-1)
2102 printf("Error: _beginthread(GetMyExternalIP) failed\n");
2102 2103
2103 // Peers that answered last time, dialled straight away. The relays are the 2104 // Peers that answered last time, dialled straight away. The relays are the
2104 // only way to find anyone otherwise, and reaching them plus walking their 2105 // only way to find anyone otherwise, and reaching them plus walking their
diff --git a/src/nostr.cpp b/src/nostr.cpp
index 9bbf74e..f44dc08 100644
--- a/src/nostr.cpp
+++ b/src/nostr.cpp
@@ -151,6 +151,19 @@ string BtfActiveRelay()
151 151
152void BtfSetActiveRelay(const string& relay) 152void BtfSetActiveRelay(const string& relay)
153{ 153{
154 // With /rvrelay set, the descriptor must never name anything but the pin.
155 // No caller can reach here with another relay today -- both registration
156 // paths draw their list from BtfAllRelays(), which returns the pin alone --
157 // but the descriptor is the one thing a miner obeys, so the invariant is
158 // enforced at the sink instead of being retrusted to every future caller.
159 if (fBtfRelayPinned &&
160 find(vBtfMeetingRelays.begin(), vBtfMeetingRelays.end(), relay) == vBtfMeetingRelays.end())
161 {
162 LogPrint("pool", "refusing to advertise meeting relay %s: /rvrelay pins %s\n",
163 relay.c_str(),
164 vBtfMeetingRelays.empty() ? "an empty list" : vBtfMeetingRelays[0].c_str());
165 return;
166 }
154 CRITICAL_BLOCK(cs_activeRelay) 167 CRITICAL_BLOCK(cs_activeRelay)
155 strBtfActiveRelay = relay; 168 strBtfActiveRelay = relay;
156} 169}
@@ -223,6 +236,18 @@ vector<string> BtfAllRelays()
223 return all; 236 return all;
224} 237}
225 238
239// Relays learned from Nostr, whether or not a pin is in force. Reporting only:
240// it exists so the pool can name what /rvrelay is excluding. Anything choosing
241// a relay to register or dial at must keep using BtfAllRelays().
242vector<string> BtfDiscoveredRelays()
243{
244 vector<string> out;
245 CRITICAL_BLOCK(cs_discoveredRelays)
246 foreach(const string& r, g_discoveredRelays)
247 out.push_back(r);
248 return out;
249}
250
226 251
227// 252//
228// Utilities 253// Utilities
diff --git a/src/nostr.h b/src/nostr.h
index 6dbbe26..0dd919d 100644
--- a/src/nostr.h
+++ b/src/nostr.h
@@ -60,6 +60,9 @@ extern bool fBtfRelayPinned;
60bool LooksLikeRelay(const std::string& r); 60bool LooksLikeRelay(const std::string& r);
61// Every relay to try: curated seeds + relays discovered from Nostr announcements. 61// Every relay to try: curated seeds + relays discovered from Nostr announcements.
62std::vector<std::string> BtfAllRelays(); 62std::vector<std::string> BtfAllRelays();
63// Relays discovered from Nostr, ignoring the pin. For reporting what a pin
64// excludes -- never for choosing a relay to register or dial at.
65std::vector<std::string> BtfDiscoveredRelays();
63 66
64struct BtfPoolAnnouncement 67struct BtfPoolAnnouncement
65{ 68{
diff --git a/src/randomx_pow.cpp b/src/randomx_pow.cpp
index 1d058d4..9c59364 100644
--- a/src/randomx_pow.cpp
+++ b/src/randomx_pow.cpp
@@ -8,6 +8,7 @@
8#include <thread> 8#include <thread>
9#include <vector> 9#include <vector>
10#include <mutex> 10#include <mutex>
11#include <system_error>
11 12
12// Fixed key (seed) that determines the RandomX cache/dataset. Keeping it 13// Fixed key (seed) that determines the RandomX cache/dataset. Keeping it
13// constant avoids per-epoch "reseed" logic; for the CPU+RAM fairness goal 14// constant avoids per-epoch "reseed" logic; for the CPU+RAM fairness goal
@@ -101,13 +102,28 @@ bool RandomXInitDataset(int nThreads)
101 102
102 std::vector<std::thread> workers; 103 std::vector<std::thread> workers;
103 unsigned long per = total / nThreads; 104 unsigned long per = total / nThreads;
104 for (int i = 0; i < nThreads; i++) 105 try
105 { 106 {
106 unsigned long start = i * per; 107 for (int i = 0; i < nThreads; i++)
107 unsigned long count = (i == nThreads - 1) ? (total - start) : per; 108 {
108 workers.emplace_back([start, count]() { 109 unsigned long start = i * per;
109 randomx_init_dataset(g_dataset, g_cache, start, count); 110 unsigned long count = (i == nThreads - 1) ? (total - start) : per;
110 }); 111 workers.emplace_back([start, count]() {
112 randomx_init_dataset(g_dataset, g_cache, start, count);
113 });
114 }
115 }
116 catch (const std::system_error& e)
117 {
118 // Same refusal as the allocation failure above: light mode is slow
119 // but alive, std::terminate is neither. Join the workers that did
120 // start before releasing the dataset out from under them.
121 for (auto& w : workers) w.join();
122 randomx_release_dataset(g_dataset);
123 g_dataset = NULL;
124 printf("RandomX: cannot spawn dataset init threads (%s), staying in light mode\n",
125 e.what());
126 return false;
111 } 127 }
112 for (auto& w : workers) w.join(); 128 for (auto& w : workers) w.join();
113 129
diff --git a/src/rpc.cpp b/src/rpc.cpp
index a4b53ca..3cee687 100644
--- a/src/rpc.cpp
+++ b/src/rpc.cpp
@@ -4947,13 +4947,19 @@ static void AcceptOneFn(void* arg)
4947 std::string host = relay.substr(0, colon); 4947 std::string host = relay.substr(0, colon);
4948 int port = atoi(relay.substr(colon + 1).c_str()); 4948 int port = atoi(relay.substr(colon + 1).c_str());
4949 4949
4950 LogPrint("pool", "[pool] accept thread started for relay %s\n", relay.c_str()); 4950 LogPrint("pool", "[pool] accept thread started for relay %s%s\n", relay.c_str(),
4951 fBtfRelayPinned ? " (/rvrelay pin)" : "");
4952
4953 // Registration health for this relay. A pin has no fallback, so a pin that
4954 // never registers means the pool is simply unreachable -- and that has to
4955 // be loud. The 2026-07-30 incident went unnoticed because this loop logged
4956 // failures at one flat line and success not at all, so "which relay is this
4957 // pool actually registered at" could not be answered from the log.
4958 int nConsecFail = 0;
4959 int64 nFirstFail = 0;
4960 bool fEverRegistered = false;
4951 4961
4952 while (!fShutdown && gPoolRunning) { 4962 while (!fShutdown && gPoolRunning) {
4953 // Advertise this relay as the pool's meeting node BEFORE registering,
4954 // so that miners which resolve our descriptor find a relay where the
4955 // pool (not the node's peer-accept) holds the registration.
4956 BtfSetActiveRelay(relay);
4957 // Returns as soon as the relay lists us -- registered, not yet paired. 4963 // Returns as soon as the relay lists us -- registered, not yet paired.
4958 btf::RvSocket rv = btf::RvServiceRegister(host.c_str(), (unsigned short)port, pk); 4964 btf::RvSocket rv = btf::RvServiceRegister(host.c_str(), (unsigned short)port, pk);
4959 4965
@@ -4962,12 +4968,36 @@ static void AcceptOneFn(void* arg)
4962 break; 4968 break;
4963 } 4969 }
4964 if (rv == btf::RV_INVALID) { 4970 if (rv == btf::RV_INVALID) {
4965 LogPrint("pool", "[pool] relay %s: RvServiceRegister failed" 4971 nConsecFail++;
4966 " -- backing off 30s before retry\n", relay.c_str()); 4972 if (nFirstFail == 0) nFirstFail = GetTime();
4973 LogPrint("pool", "[pool] relay %s: registration failed (attempt %d,"
4974 " failing for %llds) -- backing off 30s before retry\n",
4975 relay.c_str(), nConsecFail, (long long)(GetTime() - nFirstFail));
4976 if (fBtfRelayPinned && (nConsecFail == 3 || nConsecFail % 10 == 0))
4977 LogPrint("pool", "[pool] WARNING: pinned relay %s refused registration"
4978 " %d times running (%llds); /rvrelay leaves no fallback, so"
4979 " miners cannot reach this pool%s\n",
4980 relay.c_str(), nConsecFail, (long long)(GetTime() - nFirstFail),
4981 fEverRegistered ? "" : " -- it has never registered once");
4967 for (int i = 0; i < 30 && !fShutdown && gPoolRunning; i++) Sleep(1000); 4982 for (int i = 0; i < 30 && !fShutdown && gPoolRunning; i++) Sleep(1000);
4968 continue; 4983 continue;
4969 } 4984 }
4970 4985
4986 // Advertise THIS relay only now. Setting it before the call published a
4987 // meeting node we were not yet listed at, so a miner resolving the
4988 // descriptor inside that window burned its dial on a relay holding no
4989 // registration for us. net.cpp's peer-accept has always ordered it this
4990 // way round; the pool had not.
4991 BtfSetActiveRelay(relay);
4992 if (!fEverRegistered || nConsecFail > 0)
4993 LogPrint("pool", "[pool] registered at relay %s%s%s -- advertising it as"
4994 " the pool's meeting node\n", relay.c_str(),
4995 fBtfRelayPinned ? " (/rvrelay pin)" : "",
4996 nConsecFail > 0 ? ", recovered" : "");
4997 fEverRegistered = true;
4998 nConsecFail = 0;
4999 nFirstFail = 0;
5000
4971 // Block for a miner to actually arrive. RvServiceRegister used to do 5001 // Block for a miner to actually arrive. RvServiceRegister used to do
4972 // this itself and returned with the relay's 0x01 pairing byte already 5002 // this itself and returned with the relay's 0x01 pairing byte already
4973 // consumed; it no longer does. Without waiting here, BtfServiceWrap 5003 // consumed; it no longer does. Without waiting here, BtfServiceWrap
@@ -5022,9 +5052,21 @@ static void AcceptLoopFn(void*)
5022 LogPrint("pool", "[pool] .btf identity ready after %ds\n", waitSecs * 2); 5052 LogPrint("pool", "[pool] .btf identity ready after %ds\n", waitSecs * 2);
5023 5053
5024 std::set<std::string> spawned; // relays we've already started a thread for 5054 std::set<std::string> spawned; // relays we've already started a thread for
5055 std::set<std::string> skipped; // discovered relays the pin excluded, logged once each
5025 5056
5026 while (!fShutdown && gPoolRunning) { 5057 while (!fShutdown && gPoolRunning) {
5058 // BtfAllRelays() already honours the pin: with /rvrelay set it returns
5059 // vBtfMeetingRelays alone, so no thread is ever spawned for a
5060 // discovered relay. Name the ones it drops -- a pool registering at a
5061 // stranger's relay is exactly the thing that should not be silent.
5027 vector<string> relays = BtfAllRelays(); 5062 vector<string> relays = BtfAllRelays();
5063 if (fBtfRelayPinned) {
5064 for (const string& r : BtfDiscoveredRelays())
5065 if (std::find(relays.begin(), relays.end(), r) == relays.end() &&
5066 skipped.insert(r).second)
5067 LogPrint("pool", "[pool] not registering at discovered relay %s"
5068 " -- /rvrelay pins the relay list\n", r.c_str());
5069 }
5028 if (relays.empty()) { 5070 if (relays.empty()) {
5029 LogPrint("pool", "[pool] no relays available -- miners cannot connect yet\n"); 5071 LogPrint("pool", "[pool] no relays available -- miners cannot connect yet\n");
5030 } else { 5072 } else {
@@ -5040,8 +5082,9 @@ static void AcceptLoopFn(void*)
5040 relay.c_str()); 5082 relay.c_str());
5041 } else { 5083 } else {
5042 spawned.insert(relay); 5084 spawned.insert(relay);
5043 LogPrint("pool", "[pool] accept thread spawned for relay %s" 5085 LogPrint("pool", "[pool] accept thread spawned for relay %s%s"
5044 " (%zu total)\n", relay.c_str(), spawned.size()); 5086 " (%zu total)\n", relay.c_str(),
5087 fBtfRelayPinned ? " (/rvrelay pin)" : "", spawned.size());
5045 } 5088 }
5046 } 5089 }
5047 } 5090 }
@@ -5077,10 +5120,17 @@ void ThreadRPCServer(void*)
5077 // armed for its one wallet probe before it is allowed to send. 5120 // armed for its one wallet probe before it is allowed to send.
5078 ReconcilePayouts(); 5121 ReconcilePayouts();
5079 5122
5080 _beginthread(AcceptLoopFn, 0, NULL); 5123 // _beginthread cannot throw (it reports -1), but an unchecked failure
5081 _beginthread(LocalAcceptFn, 0, NULL); 5124 // leaves the pool running deaf: nobody accepts, announces, or pays, and
5082 _beginthread(ThreadBtfPoolAnnouncer, 0, NULL); 5125 // nothing in the log says why.
5083 _beginthread(PayoutThreadFn, 0, NULL); 5126 if (_beginthread(AcceptLoopFn, 0, NULL) == (uintptr_t)-1)
5127 LogPrint("pool", "[pool] FATAL: accept loop thread failed to spawn -- miners cannot connect\n");
5128 if (_beginthread(LocalAcceptFn, 0, NULL) == (uintptr_t)-1)
5129 LogPrint("pool", "[pool] local accept thread failed to spawn\n");
5130 if (_beginthread(ThreadBtfPoolAnnouncer, 0, NULL) == (uintptr_t)-1)
5131 LogPrint("pool", "[pool] announcer thread failed to spawn -- pool will not be advertised\n");
5132 if (_beginthread(PayoutThreadFn, 0, NULL) == (uintptr_t)-1)
5133 LogPrint("pool", "[pool] FATAL: payout thread failed to spawn -- no one gets paid\n");
5084 5134
5085 PoolEventLoop(); // blocks until gPoolRunning = false or fShutdown 5135 PoolEventLoop(); // blocks until gPoolRunning = false or fShutdown
5086 5136
diff --git a/src/util.h b/src/util.h
index f699e42..dc4536d 100644
--- a/src/util.h
+++ b/src/util.h
@@ -208,7 +208,7 @@ protected:
208public: 208public:
209 char* pszFile; 209 char* pszFile;
210 int nLine; 210 int nLine;
211 explicit CCriticalSection() { InitializeCriticalSection(&cs); } 211 explicit CCriticalSection() : pszFile(NULL), nLine(0) { InitializeCriticalSection(&cs); }
212 ~CCriticalSection() { DeleteCriticalSection(&cs); } 212 ~CCriticalSection() { DeleteCriticalSection(&cs); }
213 void Enter() { EnterCriticalSection(&cs); } 213 void Enter() { EnterCriticalSection(&cs); }
214 void Leave() { LeaveCriticalSection(&cs); } 214 void Leave() { LeaveCriticalSection(&cs); }