diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/Makefile | 4 | ||||
| -rw-r--r-- | src/btfrv.cpp | 49 | ||||
| -rw-r--r-- | src/btftunnel.cpp | 103 | ||||
| -rw-r--r-- | src/gui.cpp | 34 | ||||
| -rw-r--r-- | src/main.cpp | 104 | ||||
| -rw-r--r-- | src/main_gui.cpp | 50 | ||||
| -rw-r--r-- | src/net.cpp | 5 | ||||
| -rw-r--r-- | src/net.h | 28 | ||||
| -rw-r--r-- | src/nostr.cpp | 27 | ||||
| -rw-r--r-- | src/nostr.h | 3 | ||||
| -rw-r--r-- | src/randomx_pow.cpp | 28 | ||||
| -rw-r--r-- | src/rpc.cpp | 76 | ||||
| -rw-r--r-- | src/util.cpp | 54 | ||||
| -rw-r--r-- | src/util.h | 71 |
14 files changed, 581 insertions, 55 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 | ||
| 7 | SECP_INC ?= /usr/local/include | 7 | SECP_INC ?= /usr/local/include |
| 8 | SECP_LIB ?= /usr/local/lib | 8 | SECP_LIB ?= /usr/local/lib |
| 9 | RANDOMX_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. | ||
| 11 | RANDOMX_DIR ?= $(abspath $(CURDIR)/..)/randomx-build | ||
| 10 | 12 | ||
| 11 | IMGUI_DIR = imgui | 13 | IMGUI_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 | ||
| 44 | namespace btf | 46 | namespace 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 | ||
| 31 | namespace btf | 35 | namespace 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. | ||
| 138 | struct TunnelEnds | ||
| 139 | { | ||
| 140 | SOCKET pumpEnd; | ||
| 141 | RvSocket rv; | ||
| 142 | TunnelEnds(SOCKET p, RvSocket r) : pumpEnd(p), rv(r) {} | ||
| 143 | ~TunnelEnds() { BtfCloseSocket(pumpEnd); RvClose(rv); } | ||
| 144 | private: | ||
| 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. | ||
| 124 | static btf_socket_t StartTunnel(RvSocket rv, const unsigned char shared[32]) | 172 | static 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 a68e3b0..dded83a 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" |
| @@ -1712,7 +1713,7 @@ void CWalletTx::RelayWalletTransaction(CTxDB& txdb) | |||
| 1712 | uint256 hash = GetHash(); | 1713 | uint256 hash = GetHash(); |
| 1713 | if (!txdb.ContainsTx(hash)) | 1714 | if (!txdb.ContainsTx(hash)) |
| 1714 | { | 1715 | { |
| 1715 | if (LogAcceptsCategory("net")) printf("Relaying wtx %s\n", hash.ToString().substr(0,6).c_str()); | 1716 | if (LogAcceptsCategory("relay")) printf("Relaying wtx %s\n", hash.ToString().substr(0,6).c_str()); |
| 1716 | RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this); | 1717 | RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this); |
| 1717 | } | 1718 | } |
| 1718 | } | 1719 | } |
| @@ -3286,7 +3287,7 @@ bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) | |||
| 3286 | vRecv >> *pblock; | 3287 | vRecv >> *pblock; |
| 3287 | 3288 | ||
| 3288 | //// debug print | 3289 | //// debug print |
| 3289 | if (LogAcceptsCategory("net")) { printf("received block:\n"); pblock->print(); } | 3290 | if (LogAcceptsCategory("relay")) { printf("received block:\n"); pblock->print(); } |
| 3290 | 3291 | ||
| 3291 | CInv inv(MSG_BLOCK, pblock->GetHash()); | 3292 | CInv inv(MSG_BLOCK, pblock->GetHash()); |
| 3292 | pfrom->AddInventoryKnown(inv); | 3293 | pfrom->AddInventoryKnown(inv); |
| @@ -3922,9 +3923,32 @@ connected: | |||
| 3922 | std::vector<ParticipantShareHit> shareHits; | 3923 | std::vector<ParticipantShareHit> shareHits; |
| 3923 | std::mutex shareHitsMtx; | 3924 | std::mutex shareHitsMtx; |
| 3924 | std::vector<std::thread> hashThreads; | 3925 | std::vector<std::thread> hashThreads; |
| 3925 | for (int i = 0; i < nWorkers; i++) | 3926 | try |
| 3926 | hashThreads.emplace_back(ParticipantHashWorker, &jobShared, i, nWorkers, | 3927 | { |
| 3927 | &shareHits, &shareHitsMtx); | 3928 | for (int i = 0; i < nWorkers; i++) |
| 3929 | hashThreads.emplace_back(ParticipantHashWorker, &jobShared, i, nWorkers, | ||
| 3930 | &shareHits, &shareHitsMtx); | ||
| 3931 | } | ||
| 3932 | catch (const std::system_error& e) | ||
| 3933 | { | ||
| 3934 | // A refused pthread_create used to reach std::terminate here and | ||
| 3935 | // kill the worker mid-session -- observed twice on an otherwise | ||
| 3936 | // healthy participant. Stop the workers that did start the same way | ||
| 3937 | // the disconnect path below does, drop this pool connection, and let | ||
| 3938 | // the caller's reconnect loop try again once the pressure clears. | ||
| 3939 | LogPrint("worker", "[worker] cannot spawn hash threads (%s)" | ||
| 3940 | " -- dropping pool connection\n", e.what()); | ||
| 3941 | SetParticipantMiningStatus("hash thread spawn failed"); | ||
| 3942 | { | ||
| 3943 | std::lock_guard<std::mutex> lk(jobShared.mtx); | ||
| 3944 | jobShared.stop = true; | ||
| 3945 | jobShared.haveJob = false; | ||
| 3946 | } | ||
| 3947 | for (std::thread& t : hashThreads) | ||
| 3948 | t.join(); | ||
| 3949 | closesocket(s); | ||
| 3950 | return false; | ||
| 3951 | } | ||
| 3928 | LogPrint("worker", "[worker] spawned %d hash threads on shared RandomX dataset\n", | 3952 | LogPrint("worker", "[worker] spawned %d hash threads on shared RandomX dataset\n", |
| 3929 | nWorkers); | 3953 | nWorkers); |
| 3930 | const uint64 sessionStartHashes = gParticipantHashes.load(); | 3954 | const uint64 sessionStartHashes = gParticipantHashes.load(); |
| @@ -3935,6 +3959,14 @@ connected: | |||
| 3935 | std::string jobId; | 3959 | std::string jobId; |
| 3936 | unsigned char header[80] = {}; | 3960 | unsigned char header[80] = {}; |
| 3937 | uint256 target; | 3961 | uint256 target; |
| 3962 | // Cached answer to "which block is this job built on", for the | ||
| 3963 | // mining.notify handler below -- see the comment there. Session-local, so | ||
| 3964 | // a reconnect re-resolves rather than trusting an answer obtained before | ||
| 3965 | // a possible change of pool. | ||
| 3966 | uint256 hashPrevResolved; // prevhash the cached answer describes | ||
| 3967 | bool fPrevResolved = false; // whether that answer exists yet | ||
| 3968 | int nPrevHeight = -1; // its height, or -1 == unknown to us | ||
| 3969 | int nBestHeightResolved = -1; // nBestHeight when we last resolved | ||
| 3938 | double currentDifficulty = 1.0; // updated by mining.set_difficulty from pool | 3970 | double currentDifficulty = 1.0; // updated by mining.set_difficulty from pool |
| 3939 | bool haveJob = false; | 3971 | bool haveJob = false; |
| 3940 | bool gotSubscribeAck = false; | 3972 | bool gotSubscribeAck = false; |
| @@ -4063,8 +4095,64 @@ connected: | |||
| 4063 | jobShared.jobSeq++; | 4095 | jobShared.jobSeq++; |
| 4064 | jobShared.haveJob = true; | 4096 | jobShared.haveJob = true; |
| 4065 | } | 4097 | } |
| 4066 | LogPrint("worker", "[pool->worker] new job %s received\n", | 4098 | // Log the chain position the pool is |
| 4067 | jobId.c_str()); | 4099 | // building on, so a stale or private |
| 4100 | // fork is auditable from worker logs. | ||
| 4101 | // The prevhash comes from the header we | ||
| 4102 | // actually hash (== p[2] of the notify); | ||
| 4103 | // a brief cs_main lookup is safe here -- | ||
| 4104 | // this thread holds no other lock. | ||
| 4105 | // | ||
| 4106 | // Resolving it is the expensive half, and | ||
| 4107 | // this is the socket-reading thread: block | ||
| 4108 | // validation can hold cs_main for a long | ||
| 4109 | // time, and every moment spent waiting on | ||
| 4110 | // it here is a moment set_difficulty and | ||
| 4111 | // share responses are not being handled. | ||
| 4112 | // Most notifies in a round are a new job | ||
| 4113 | // on the SAME tip, so the answer is cached | ||
| 4114 | // and re-resolved only when it could come | ||
| 4115 | // out differently: a prevhash we have not | ||
| 4116 | // resolved, or one we could NOT resolve | ||
| 4117 | // last time while the chain has since | ||
| 4118 | // moved (unknown -> known). A block's | ||
| 4119 | // height is fixed once mapBlockIndex knows | ||
| 4120 | // it, so a cached "known" never goes | ||
| 4121 | // stale. nBestHeight is read unlocked on | ||
| 4122 | // purpose -- it only decides whether to | ||
| 4123 | // repeat a lookup, never what gets | ||
| 4124 | // printed, so a stale read costs at most | ||
| 4125 | // one deferred or one extra lookup. | ||
| 4126 | // The line still prints in full for every | ||
| 4127 | // job, cached or not. | ||
| 4128 | uint256 hashPrev; | ||
| 4129 | memcpy(&hashPrev, header + 4, 32); | ||
| 4130 | if (LogAcceptsCategory("worker")) | ||
| 4131 | { | ||
| 4132 | int nBestHeightNow = nBestHeight; | ||
| 4133 | if (!fPrevResolved | ||
| 4134 | || hashPrev != hashPrevResolved | ||
| 4135 | || (nPrevHeight < 0 && nBestHeightNow != nBestHeightResolved)) | ||
| 4136 | { | ||
| 4137 | nPrevHeight = -1; | ||
| 4138 | CRITICAL_BLOCK(cs_main) | ||
| 4139 | { | ||
| 4140 | map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrev); | ||
| 4141 | if (mi != mapBlockIndex.end()) | ||
| 4142 | nPrevHeight = (*mi).second->nHeight; | ||
| 4143 | } | ||
| 4144 | hashPrevResolved = hashPrev; | ||
| 4145 | nBestHeightResolved = nBestHeightNow; | ||
| 4146 | fPrevResolved = true; | ||
| 4147 | } | ||
| 4148 | if (nPrevHeight >= 0) | ||
| 4149 | LogPrint("worker", "[pool->worker] new job %s received, prevhash %s (known, job height %d)\n", | ||
| 4150 | jobId.c_str(), hashPrev.GetHex().c_str(), | ||
| 4151 | nPrevHeight + 1); | ||
| 4152 | else | ||
| 4153 | LogPrint("worker", "[pool->worker] new job %s received, prevhash %s (unknown to our chain)\n", | ||
| 4154 | jobId.c_str(), hashPrev.GetHex().c_str()); | ||
| 4155 | } | ||
| 4068 | SetParticipantMiningStatus("hashing job " + jobId); | 4156 | SetParticipantMiningStatus("hashing job " + jobId); |
| 4069 | } | 4157 | } |
| 4070 | } | 4158 | } |
| @@ -4578,7 +4666,7 @@ bool BitcoinMiner(int nThreadId) | |||
| 4578 | //// debug print | 4666 | //// debug print |
| 4579 | if (LogAcceptsCategory("net")) printf("BitcoinMiner:\n"); | 4667 | if (LogAcceptsCategory("net")) printf("BitcoinMiner:\n"); |
| 4580 | if (LogAcceptsCategory("net")) printf("RandomX proof-of-work found \n powhash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str()); | 4668 | if (LogAcceptsCategory("net")) printf("RandomX proof-of-work found \n powhash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str()); |
| 4581 | if (LogAcceptsCategory("net")) pblock->print(); | 4669 | if (LogAcceptsCategory("relay")) pblock->print(); |
| 4582 | 4670 | ||
| 4583 | SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); | 4671 | SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); |
| 4584 | CRITICAL_BLOCK(cs_main) | 4672 | CRITICAL_BLOCK(cs_main) |
diff --git a/src/main_gui.cpp b/src/main_gui.cpp index 211e1e2..0e64985 100644 --- a/src/main_gui.cpp +++ b/src/main_gui.cpp | |||
| @@ -111,6 +111,8 @@ static void PrintUsage() | |||
| 111 | printf(" /help, -help, --help, /?\n"); | 111 | printf(" /help, -help, --help, /?\n"); |
| 112 | printf(" /datadir=PATH\n"); | 112 | printf(" /datadir=PATH\n"); |
| 113 | printf(" /debug\n"); | 113 | printf(" /debug\n"); |
| 114 | printf(" /debugrelay (/debug plus per-message relay chatter and block dumps)\n"); | ||
| 115 | printf(" /maxdebugfilesize=N (roll debug.log at N MB, default 1024; 0 = never)\n"); | ||
| 114 | printf(" /gen\n"); | 116 | printf(" /gen\n"); |
| 115 | printf(" /nogui or /daemon\n"); | 117 | printf(" /nogui or /daemon\n"); |
| 116 | printf(" /selftest=wallet-keypool, wallet-hd, wallet-format, wallet-crypto, wallet-encrypt,\n"); | 118 | printf(" /selftest=wallet-keypool, wallet-hd, wallet-format, wallet-crypto, wallet-encrypt,\n"); |
| @@ -191,6 +193,54 @@ static void ParseStartupArguments(int argc, char* argv[]) | |||
| 191 | if (arg(argc,argv,"/debug") || arg(argc,argv,"-debug")) | 193 | if (arg(argc,argv,"/debug") || arg(argc,argv,"-debug")) |
| 192 | fDebug = true; | 194 | fDebug = true; |
| 193 | 195 | ||
| 196 | // /debugrelay -- everything /debug shows, plus the per-message firehose | ||
| 197 | // ("relay" and "nostrdiscovery" categories: sending: tx, Relaying wtx, | ||
| 198 | // raw CBlock dumps, per-peer discovery lines). That traffic was ~90% of | ||
| 199 | // a 13-hour production debug.log (issue #35), so plain /debug leaves it | ||
| 200 | // off; the message text itself is unchanged for anyone grepping it. | ||
| 201 | if (arg(argc,argv,"/debugrelay") || arg(argc,argv,"-debugrelay")) | ||
| 202 | { | ||
| 203 | fDebug = true; | ||
| 204 | fDebugRelay = true; | ||
| 205 | } | ||
| 206 | |||
| 207 | // /maxdebugfilesize=N -- roll debug.log to debug.log.old once it passes | ||
| 208 | // N MB, checked on each write. Default is 1024 (see util.cpp); 0 turns | ||
| 209 | // the check off and leaves rotation entirely to logrotate. | ||
| 210 | string strMaxDebugSize = argval2(argc, argv, "/maxdebugfilesize", "-maxdebugfilesize"); | ||
| 211 | if (!strMaxDebugSize.empty()) | ||
| 212 | { | ||
| 213 | // Parsed with atoi64() before, which is strtoll() with the endptr | ||
| 214 | // thrown away: it returns 0 for anything it cannot read, so | ||
| 215 | // /maxdebugfilesize=1G and =1024MB both came out as 0 -- "never | ||
| 216 | // roll", identical to asking for that on purpose, with nothing said | ||
| 217 | // to the operator. The old code also multiplied without a range | ||
| 218 | // check, so a big enough N wrapped to a negative cap, which the roll | ||
| 219 | // reads as "off" too. Every rejection is now reported and leaves the | ||
| 220 | // default in place; the value is a plain count of MB, no suffix. | ||
| 221 | const char* psz = strMaxDebugSize.c_str(); | ||
| 222 | char* pszEnd = NULL; | ||
| 223 | errno = 0; | ||
| 224 | int64 nMB = strtoll(psz, &pszEnd, 10); | ||
| 225 | // INT64_MAX, without depending on which limits header this tree pulls in. | ||
| 226 | const int64 nMaxMB = (int64)((~(uint64)0) >> 1) / (1024 * 1024); | ||
| 227 | const char* pszWhy = NULL; | ||
| 228 | if (pszEnd == psz) | ||
| 229 | pszWhy = "not a number"; | ||
| 230 | else if (*pszEnd != '\0') | ||
| 231 | pszWhy = "trailing characters -- the value is a count of MB, with no unit suffix"; | ||
| 232 | else if (errno == ERANGE || nMB < 0) | ||
| 233 | pszWhy = "not a size in MB"; | ||
| 234 | else if (nMB > nMaxMB) | ||
| 235 | pszWhy = "larger than a file size can be"; | ||
| 236 | if (pszWhy) | ||
| 237 | fprintf(stderr, "Ignoring /maxdebugfilesize=%s: %s (keeping %lld MB)\n", | ||
| 238 | strMaxDebugSize.c_str(), pszWhy, | ||
| 239 | (long long)(nMaxDebugFileSize / 1024 / 1024)); | ||
| 240 | else | ||
| 241 | nMaxDebugFileSize = nMB * 1024 * 1024; | ||
| 242 | } | ||
| 243 | |||
| 194 | if (arg(argc,argv,"/gen") || arg(argc,argv,"-gen")) | 244 | if (arg(argc,argv,"/gen") || arg(argc,argv,"-gen")) |
| 195 | { | 245 | { |
| 196 | fGenerateBitcoins = 1; | 246 | fGenerateBitcoins = 1; |
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 |
| @@ -802,6 +802,18 @@ public: | |||
| 802 | 802 | ||
| 803 | 803 | ||
| 804 | 804 | ||
| 805 | // "sending: tx (N bytes)" alone was ~71% of a 13-hour production | ||
| 806 | // debug.log (issue #35), so tx sends are demoted to the /debugrelay-gated | ||
| 807 | // "relay" category; every other command's send trace stays on "net". | ||
| 808 | // The line is emitted in pieces across BeginMessage/EndMessage/ | ||
| 809 | // AbortMessage, so all three must agree on the category or orphaned | ||
| 810 | // "(N bytes)" fragments would leak into a plain -debug log. | ||
| 811 | // Valid only mid-message (nPushPos != -1). | ||
| 812 | const char* SendLogCategory() const | ||
| 813 | { | ||
| 814 | return strcmp(GetMessageCommand(), "tx") == 0 ? "relay" : "net"; | ||
| 815 | } | ||
| 816 | |||
| 805 | void BeginMessage(const char* pszCommand) | 817 | void BeginMessage(const char* pszCommand) |
| 806 | { | 818 | { |
| 807 | EnterCriticalSection(&cs_vSend); | 819 | EnterCriticalSection(&cs_vSend); |
| @@ -809,17 +821,19 @@ public: | |||
| 809 | AbortMessage(); | 821 | AbortMessage(); |
| 810 | nPushPos = vSend.size(); | 822 | nPushPos = vSend.size(); |
| 811 | vSend << CMessageHeader(pszCommand, 0); | 823 | vSend << CMessageHeader(pszCommand, 0); |
| 812 | if (LogAcceptsCategory("net")) printf("sending: %-12s ", pszCommand); | 824 | if (LogAcceptsCategory(SendLogCategory())) printf("sending: %-12s ", pszCommand); |
| 813 | } | 825 | } |
| 814 | 826 | ||
| 815 | void AbortMessage() | 827 | void AbortMessage() |
| 816 | { | 828 | { |
| 817 | if (nPushPos == -1) | 829 | if (nPushPos == -1) |
| 818 | return; | 830 | return; |
| 831 | // Capture before nPushPos is cleared; GetMessageCommand() needs it. | ||
| 832 | const char* pszCategory = SendLogCategory(); | ||
| 819 | vSend.resize(nPushPos); | 833 | vSend.resize(nPushPos); |
| 820 | nPushPos = -1; | 834 | nPushPos = -1; |
| 821 | LeaveCriticalSection(&cs_vSend); | 835 | LeaveCriticalSection(&cs_vSend); |
| 822 | if (LogAcceptsCategory("net")) printf("(aborted)\n"); | 836 | if (LogAcceptsCategory(pszCategory)) printf("(aborted)\n"); |
| 823 | } | 837 | } |
| 824 | 838 | ||
| 825 | void EndMessage() | 839 | void EndMessage() |
| @@ -827,7 +841,11 @@ public: | |||
| 827 | extern int nDropMessagesTest; | 841 | extern int nDropMessagesTest; |
| 828 | if (nDropMessagesTest > 0 && GetRand(nDropMessagesTest) == 0) | 842 | if (nDropMessagesTest > 0 && GetRand(nDropMessagesTest) == 0) |
| 829 | { | 843 | { |
| 830 | if (LogAcceptsCategory("net")) printf("dropmessages DROPPING SEND MESSAGE\n"); | 844 | // Same category as the "sending: " this line interrupts, so a tx |
| 845 | // does not announce its own drop under "net" having been gated | ||
| 846 | // off under "relay". nPushPos can be -1 here, and then | ||
| 847 | // GetMessageCommand() returns "" and this is "net" as before. | ||
| 848 | if (LogAcceptsCategory(SendLogCategory())) printf("dropmessages DROPPING SEND MESSAGE\n"); | ||
| 831 | AbortMessage(); | 849 | AbortMessage(); |
| 832 | return; | 850 | return; |
| 833 | } | 851 | } |
| @@ -839,10 +857,10 @@ public: | |||
| 839 | unsigned int nSize = vSend.size() - nPushPos - sizeof(CMessageHeader); | 857 | unsigned int nSize = vSend.size() - nPushPos - sizeof(CMessageHeader); |
| 840 | memcpy((char*)&vSend[nPushPos] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize)); | 858 | memcpy((char*)&vSend[nPushPos] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize)); |
| 841 | 859 | ||
| 842 | if (LogAcceptsCategory("net")) printf("(%d bytes) ", nSize); | 860 | if (LogAcceptsCategory(SendLogCategory())) printf("(%d bytes) ", nSize); |
| 843 | //for (int i = nPushPos+sizeof(CMessageHeader); i < min(vSend.size(), nPushPos+sizeof(CMessageHeader)+20U); i++) | 861 | //for (int i = nPushPos+sizeof(CMessageHeader); i < min(vSend.size(), nPushPos+sizeof(CMessageHeader)+20U); i++) |
| 844 | // printf("%02x ", vSend[i] & 0xff); | 862 | // printf("%02x ", vSend[i] & 0xff); |
| 845 | if (LogAcceptsCategory("net")) printf("\n"); | 863 | if (LogAcceptsCategory(SendLogCategory())) printf("\n"); |
| 846 | 864 | ||
| 847 | nPushPos = -1; | 865 | nPushPos = -1; |
| 848 | LeaveCriticalSection(&cs_vSend); | 866 | LeaveCriticalSection(&cs_vSend); |
diff --git a/src/nostr.cpp b/src/nostr.cpp index e2d839c..f44dc08 100644 --- a/src/nostr.cpp +++ b/src/nostr.cpp | |||
| @@ -151,6 +151,19 @@ string BtfActiveRelay() | |||
| 151 | 151 | ||
| 152 | void BtfSetActiveRelay(const string& relay) | 152 | void 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(). | ||
| 242 | vector<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 |
| @@ -1440,7 +1465,7 @@ static bool SeedFromRelay(CNostrKey& key, const string& relay) | |||
| 1440 | else if (createdAt > it->second) it->second = createdAt; // refresh | 1465 | else if (createdAt > it->second) it->second = createdAt; // refresh |
| 1441 | } | 1466 | } |
| 1442 | if (fNew && fDebug) | 1467 | if (fNew && fDebug) |
| 1443 | LogPrint("nostr", "Nostr: discovered .btf peer %s\n", peerAddr.c_str()); | 1468 | LogPrint("nostrdiscovery", "Nostr: discovered .btf peer %s\n", peerAddr.c_str()); |
| 1444 | if (++nPeers > 500) break; | 1469 | if (++nPeers > 500) break; |
| 1445 | } | 1470 | } |
| 1446 | else if (type == "EOSE") | 1471 | else if (type == "EOSE") |
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; | |||
| 60 | bool LooksLikeRelay(const std::string& r); | 60 | bool 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. |
| 62 | std::vector<std::string> BtfAllRelays(); | 62 | std::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. | ||
| 65 | std::vector<std::string> BtfDiscoveredRelays(); | ||
| 63 | 66 | ||
| 64 | struct BtfPoolAnnouncement | 67 | struct 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 6531fe8..bd5fd8b 100644 --- a/src/rpc.cpp +++ b/src/rpc.cpp | |||
| @@ -4949,13 +4949,19 @@ static void AcceptOneFn(void* arg) | |||
| 4949 | std::string host = relay.substr(0, colon); | 4949 | std::string host = relay.substr(0, colon); |
| 4950 | int port = atoi(relay.substr(colon + 1).c_str()); | 4950 | int port = atoi(relay.substr(colon + 1).c_str()); |
| 4951 | 4951 | ||
| 4952 | LogPrint("pool", "[pool] accept thread started for relay %s\n", relay.c_str()); | 4952 | LogPrint("pool", "[pool] accept thread started for relay %s%s\n", relay.c_str(), |
| 4953 | fBtfRelayPinned ? " (/rvrelay pin)" : ""); | ||
| 4954 | |||
| 4955 | // Registration health for this relay. A pin has no fallback, so a pin that | ||
| 4956 | // never registers means the pool is simply unreachable -- and that has to | ||
| 4957 | // be loud. The 2026-07-30 incident went unnoticed because this loop logged | ||
| 4958 | // failures at one flat line and success not at all, so "which relay is this | ||
| 4959 | // pool actually registered at" could not be answered from the log. | ||
| 4960 | int nConsecFail = 0; | ||
| 4961 | int64 nFirstFail = 0; | ||
| 4962 | bool fEverRegistered = false; | ||
| 4953 | 4963 | ||
| 4954 | while (!fShutdown && gPoolRunning) { | 4964 | while (!fShutdown && gPoolRunning) { |
| 4955 | // Advertise this relay as the pool's meeting node BEFORE registering, | ||
| 4956 | // so that miners which resolve our descriptor find a relay where the | ||
| 4957 | // pool (not the node's peer-accept) holds the registration. | ||
| 4958 | BtfSetActiveRelay(relay); | ||
| 4959 | // Returns as soon as the relay lists us -- registered, not yet paired. | 4965 | // Returns as soon as the relay lists us -- registered, not yet paired. |
| 4960 | btf::RvSocket rv = btf::RvServiceRegister(host.c_str(), (unsigned short)port, pk); | 4966 | btf::RvSocket rv = btf::RvServiceRegister(host.c_str(), (unsigned short)port, pk); |
| 4961 | 4967 | ||
| @@ -4964,12 +4970,36 @@ static void AcceptOneFn(void* arg) | |||
| 4964 | break; | 4970 | break; |
| 4965 | } | 4971 | } |
| 4966 | if (rv == btf::RV_INVALID) { | 4972 | if (rv == btf::RV_INVALID) { |
| 4967 | LogPrint("pool", "[pool] relay %s: RvServiceRegister failed" | 4973 | nConsecFail++; |
| 4968 | " -- backing off 30s before retry\n", relay.c_str()); | 4974 | if (nFirstFail == 0) nFirstFail = GetTime(); |
| 4975 | LogPrint("pool", "[pool] relay %s: registration failed (attempt %d," | ||
| 4976 | " failing for %llds) -- backing off 30s before retry\n", | ||
| 4977 | relay.c_str(), nConsecFail, (long long)(GetTime() - nFirstFail)); | ||
| 4978 | if (fBtfRelayPinned && (nConsecFail == 3 || nConsecFail % 10 == 0)) | ||
| 4979 | LogPrint("pool", "[pool] WARNING: pinned relay %s refused registration" | ||
| 4980 | " %d times running (%llds); /rvrelay leaves no fallback, so" | ||
| 4981 | " miners cannot reach this pool%s\n", | ||
| 4982 | relay.c_str(), nConsecFail, (long long)(GetTime() - nFirstFail), | ||
| 4983 | fEverRegistered ? "" : " -- it has never registered once"); | ||
| 4969 | for (int i = 0; i < 30 && !fShutdown && gPoolRunning; i++) Sleep(1000); | 4984 | for (int i = 0; i < 30 && !fShutdown && gPoolRunning; i++) Sleep(1000); |
| 4970 | continue; | 4985 | continue; |
| 4971 | } | 4986 | } |
| 4972 | 4987 | ||
| 4988 | // Advertise THIS relay only now. Setting it before the call published a | ||
| 4989 | // meeting node we were not yet listed at, so a miner resolving the | ||
| 4990 | // descriptor inside that window burned its dial on a relay holding no | ||
| 4991 | // registration for us. net.cpp's peer-accept has always ordered it this | ||
| 4992 | // way round; the pool had not. | ||
| 4993 | BtfSetActiveRelay(relay); | ||
| 4994 | if (!fEverRegistered || nConsecFail > 0) | ||
| 4995 | LogPrint("pool", "[pool] registered at relay %s%s%s -- advertising it as" | ||
| 4996 | " the pool's meeting node\n", relay.c_str(), | ||
| 4997 | fBtfRelayPinned ? " (/rvrelay pin)" : "", | ||
| 4998 | nConsecFail > 0 ? ", recovered" : ""); | ||
| 4999 | fEverRegistered = true; | ||
| 5000 | nConsecFail = 0; | ||
| 5001 | nFirstFail = 0; | ||
| 5002 | |||
| 4973 | // Block for a miner to actually arrive. RvServiceRegister used to do | 5003 | // Block for a miner to actually arrive. RvServiceRegister used to do |
| 4974 | // this itself and returned with the relay's 0x01 pairing byte already | 5004 | // this itself and returned with the relay's 0x01 pairing byte already |
| 4975 | // consumed; it no longer does. Without waiting here, BtfServiceWrap | 5005 | // consumed; it no longer does. Without waiting here, BtfServiceWrap |
| @@ -5024,9 +5054,21 @@ static void AcceptLoopFn(void*) | |||
| 5024 | LogPrint("pool", "[pool] .btf identity ready after %ds\n", waitSecs * 2); | 5054 | LogPrint("pool", "[pool] .btf identity ready after %ds\n", waitSecs * 2); |
| 5025 | 5055 | ||
| 5026 | std::set<std::string> spawned; // relays we've already started a thread for | 5056 | std::set<std::string> spawned; // relays we've already started a thread for |
| 5057 | std::set<std::string> skipped; // discovered relays the pin excluded, logged once each | ||
| 5027 | 5058 | ||
| 5028 | while (!fShutdown && gPoolRunning) { | 5059 | while (!fShutdown && gPoolRunning) { |
| 5060 | // BtfAllRelays() already honours the pin: with /rvrelay set it returns | ||
| 5061 | // vBtfMeetingRelays alone, so no thread is ever spawned for a | ||
| 5062 | // discovered relay. Name the ones it drops -- a pool registering at a | ||
| 5063 | // stranger's relay is exactly the thing that should not be silent. | ||
| 5029 | vector<string> relays = BtfAllRelays(); | 5064 | vector<string> relays = BtfAllRelays(); |
| 5065 | if (fBtfRelayPinned) { | ||
| 5066 | for (const string& r : BtfDiscoveredRelays()) | ||
| 5067 | if (std::find(relays.begin(), relays.end(), r) == relays.end() && | ||
| 5068 | skipped.insert(r).second) | ||
| 5069 | LogPrint("pool", "[pool] not registering at discovered relay %s" | ||
| 5070 | " -- /rvrelay pins the relay list\n", r.c_str()); | ||
| 5071 | } | ||
| 5030 | if (relays.empty()) { | 5072 | if (relays.empty()) { |
| 5031 | LogPrint("pool", "[pool] no relays available -- miners cannot connect yet\n"); | 5073 | LogPrint("pool", "[pool] no relays available -- miners cannot connect yet\n"); |
| 5032 | } else { | 5074 | } else { |
| @@ -5042,8 +5084,9 @@ static void AcceptLoopFn(void*) | |||
| 5042 | relay.c_str()); | 5084 | relay.c_str()); |
| 5043 | } else { | 5085 | } else { |
| 5044 | spawned.insert(relay); | 5086 | spawned.insert(relay); |
| 5045 | LogPrint("pool", "[pool] accept thread spawned for relay %s" | 5087 | LogPrint("pool", "[pool] accept thread spawned for relay %s%s" |
| 5046 | " (%zu total)\n", relay.c_str(), spawned.size()); | 5088 | " (%zu total)\n", relay.c_str(), |
| 5089 | fBtfRelayPinned ? " (/rvrelay pin)" : "", spawned.size()); | ||
| 5047 | } | 5090 | } |
| 5048 | } | 5091 | } |
| 5049 | } | 5092 | } |
| @@ -5079,10 +5122,17 @@ void ThreadRPCServer(void*) | |||
| 5079 | // armed for its one wallet probe before it is allowed to send. | 5122 | // armed for its one wallet probe before it is allowed to send. |
| 5080 | ReconcilePayouts(); | 5123 | ReconcilePayouts(); |
| 5081 | 5124 | ||
| 5082 | _beginthread(AcceptLoopFn, 0, NULL); | 5125 | // _beginthread cannot throw (it reports -1), but an unchecked failure |
| 5083 | _beginthread(LocalAcceptFn, 0, NULL); | 5126 | // leaves the pool running deaf: nobody accepts, announces, or pays, and |
| 5084 | _beginthread(ThreadBtfPoolAnnouncer, 0, NULL); | 5127 | // nothing in the log says why. |
| 5085 | _beginthread(PayoutThreadFn, 0, NULL); | 5128 | if (_beginthread(AcceptLoopFn, 0, NULL) == (uintptr_t)-1) |
| 5129 | LogPrint("pool", "[pool] FATAL: accept loop thread failed to spawn -- miners cannot connect\n"); | ||
| 5130 | if (_beginthread(LocalAcceptFn, 0, NULL) == (uintptr_t)-1) | ||
| 5131 | LogPrint("pool", "[pool] local accept thread failed to spawn\n"); | ||
| 5132 | if (_beginthread(ThreadBtfPoolAnnouncer, 0, NULL) == (uintptr_t)-1) | ||
| 5133 | LogPrint("pool", "[pool] announcer thread failed to spawn -- pool will not be advertised\n"); | ||
| 5134 | if (_beginthread(PayoutThreadFn, 0, NULL) == (uintptr_t)-1) | ||
| 5135 | LogPrint("pool", "[pool] FATAL: payout thread failed to spawn -- no one gets paid\n"); | ||
| 5086 | 5136 | ||
| 5087 | PoolEventLoop(); // blocks until gPoolRunning = false or fShutdown | 5137 | PoolEventLoop(); // blocks until gPoolRunning = false or fShutdown |
| 5088 | 5138 | ||
diff --git a/src/util.cpp b/src/util.cpp index b5b145f..ab29178 100644 --- a/src/util.cpp +++ b/src/util.cpp | |||
| @@ -7,6 +7,12 @@ | |||
| 7 | 7 | ||
| 8 | 8 | ||
| 9 | bool fDebug = false; | 9 | bool fDebug = false; |
| 10 | bool fDebugRelay = false; | ||
| 11 | |||
| 12 | // In-process cap for debug.log, in bytes. Default matches the 1G trigger of | ||
| 13 | // the shipped logrotate policy so a long-running node stays bounded even | ||
| 14 | // without it; -maxdebugfilesize=N (MB) tunes it, 0 disables. | ||
| 15 | int64 nMaxDebugFileSize = 1024 * 1024 * (int64)1024; | ||
| 10 | 16 | ||
| 11 | // --------------------------------------------------------------------------- | 17 | // --------------------------------------------------------------------------- |
| 12 | // Categorized, burst-collapsing logging -- see the LogPrint doc comment in | 18 | // Categorized, burst-collapsing logging -- see the LogPrint doc comment in |
| @@ -26,10 +32,22 @@ static bool LogCategoryDefaultOn(const char* category) | |||
| 26 | strcmp(category, "payout") == 0; | 32 | strcmp(category, "payout") == 0; |
| 27 | } | 33 | } |
| 28 | 34 | ||
| 35 | // Categories so noisy they drown out everything else even under -debug: | ||
| 36 | // per-message send traces, wallet relay rebroadcasts, raw CBlock dumps and | ||
| 37 | // per-address discovery lines made up ~90% of a 13-hour production capture | ||
| 38 | // (issue #35). They need /debugrelay, not merely /debug. | ||
| 39 | static bool LogCategoryVerboseOnly(const char* category) | ||
| 40 | { | ||
| 41 | return strcmp(category, "relay") == 0 || | ||
| 42 | strcmp(category, "nostrdiscovery") == 0; | ||
| 43 | } | ||
| 44 | |||
| 29 | bool LogAcceptsCategory(const char* category) | 45 | bool LogAcceptsCategory(const char* category) |
| 30 | { | 46 | { |
| 31 | if (LogCategoryDefaultOn(category)) | 47 | if (LogCategoryDefaultOn(category)) |
| 32 | return true; | 48 | return true; |
| 49 | if (LogCategoryVerboseOnly(category)) | ||
| 50 | return fDebugRelay; | ||
| 33 | return fDebug; | 51 | return fDebug; |
| 34 | } | 52 | } |
| 35 | 53 | ||
| @@ -478,13 +496,37 @@ bool FileExists(const char* psz) | |||
| 478 | #endif | 496 | #endif |
| 479 | } | 497 | } |
| 480 | 498 | ||
| 481 | int GetFilesize(FILE* file) | 499 | #ifndef _WIN32 |
| 500 | // If off_t is 32 bits wide, ftello() truncates exactly like the int this | ||
| 501 | // function used to return. Fail the build rather than ship the silent | ||
| 502 | // version of the bug (32-bit hosts need -D_FILE_OFFSET_BITS=64). | ||
| 503 | static_assert(sizeof(off_t) >= 8, "GetFilesize needs a 64-bit off_t"); | ||
| 504 | #endif | ||
| 505 | |||
| 506 | // Returns the file's size in bytes, or -1 if it cannot be determined. | ||
| 507 | // | ||
| 508 | // This used to hold ftell()'s long in an int, so a file of 2 GiB or more came | ||
| 509 | // back negative. Its only caller is the debug.log roll in util.h, which skips | ||
| 510 | // the roll on a negative size -- i.e. rotation switched itself off for good at | ||
| 511 | // exactly the size the roll exists to prevent, and any cap of 2048 MB or more | ||
| 512 | // could never be exceeded at all. Both failures were silent. | ||
| 513 | int64 GetFilesize(FILE* file) | ||
| 482 | { | 514 | { |
| 483 | int nSavePos = ftell(file); | 515 | #ifdef _WIN32 |
| 484 | int nFilesize = -1; | 516 | __int64 nSavePos = _ftelli64(file); |
| 485 | if (fseek(file, 0, SEEK_END) == 0) | 517 | int64 nFilesize = -1; |
| 486 | nFilesize = ftell(file); | 518 | if (nSavePos >= 0 && _fseeki64(file, 0, SEEK_END) == 0) |
| 487 | fseek(file, nSavePos, SEEK_SET); | 519 | nFilesize = _ftelli64(file); |
| 520 | if (nSavePos >= 0) | ||
| 521 | _fseeki64(file, nSavePos, SEEK_SET); | ||
| 522 | #else | ||
| 523 | off_t nSavePos = ftello(file); | ||
| 524 | int64 nFilesize = -1; | ||
| 525 | if (nSavePos >= 0 && fseeko(file, 0, SEEK_END) == 0) | ||
| 526 | nFilesize = ftello(file); | ||
| 527 | if (nSavePos >= 0) | ||
| 528 | fseeko(file, nSavePos, SEEK_SET); | ||
| 529 | #endif | ||
| 488 | return nFilesize; | 530 | return nFilesize; |
| 489 | } | 531 | } |
| 490 | 532 | ||
| @@ -87,6 +87,15 @@ inline T& REF(const T& val) | |||
| 87 | 87 | ||
| 88 | extern bool fDebug; | 88 | extern bool fDebug; |
| 89 | 89 | ||
| 90 | // /debugrelay: the per-message firehose ("relay" and "nostrdiscovery" | ||
| 91 | // categories) that even -debug keeps off. See LogAcceptsCategory(). | ||
| 92 | extern bool fDebugRelay; | ||
| 93 | |||
| 94 | // debug.log is rolled to debug.log.old once it grows past this many bytes | ||
| 95 | // (set from -maxdebugfilesize, in MB; 0 disables the check). See the roll | ||
| 96 | // site in OutputDebugStringF() below. | ||
| 97 | extern int64 nMaxDebugFileSize; | ||
| 98 | |||
| 90 | // --------------------------------------------------------------------------- | 99 | // --------------------------------------------------------------------------- |
| 91 | // Categorized, burst-collapsing logging | 100 | // Categorized, burst-collapsing logging |
| 92 | // | 101 | // |
| @@ -159,7 +168,7 @@ void ParseString(const string& str, char c, vector<string>& v); | |||
| 159 | string FormatMoney(int64 n, bool fPlus=false); | 168 | string FormatMoney(int64 n, bool fPlus=false); |
| 160 | bool ParseMoney(const char* pszIn, int64& nRet); | 169 | bool ParseMoney(const char* pszIn, int64& nRet); |
| 161 | bool FileExists(const char* psz); | 170 | bool FileExists(const char* psz); |
| 162 | int GetFilesize(FILE* file); | 171 | int64 GetFilesize(FILE* file); |
| 163 | uint64 GetRand(uint64 nMax); | 172 | uint64 GetRand(uint64 nMax); |
| 164 | int64 GetTime(); | 173 | int64 GetTime(); |
| 165 | int64 GetAdjustedTime(); | 174 | int64 GetAdjustedTime(); |
| @@ -213,7 +222,7 @@ protected: | |||
| 213 | public: | 222 | public: |
| 214 | char* pszFile; | 223 | char* pszFile; |
| 215 | int nLine; | 224 | int nLine; |
| 216 | explicit CCriticalSection() { InitializeCriticalSection(&cs); } | 225 | explicit CCriticalSection() : pszFile(NULL), nLine(0) { InitializeCriticalSection(&cs); } |
| 217 | ~CCriticalSection() { DeleteCriticalSection(&cs); } | 226 | ~CCriticalSection() { DeleteCriticalSection(&cs); } |
| 218 | void Enter() { EnterCriticalSection(&cs); } | 227 | void Enter() { EnterCriticalSection(&cs); } |
| 219 | void Leave() { LeaveCriticalSection(&cs); } | 228 | void Leave() { LeaveCriticalSection(&cs); } |
| @@ -404,7 +413,65 @@ inline int OutputDebugStringF(const char* pszFormat, ...) | |||
| 404 | else | 413 | else |
| 405 | strDebugFile = "debug.log"; | 414 | strDebugFile = "debug.log"; |
| 406 | } | 415 | } |
| 416 | // Latched by a failed rename in the roll below, which cannot be | ||
| 417 | // retried usefully and must not be retried endlessly. | ||
| 418 | static bool fRollDisabled = false; | ||
| 407 | FILE* fileout = fopen(strDebugFile.c_str(), "a"); | 419 | FILE* fileout = fopen(strDebugFile.c_str(), "a"); |
| 420 | if (fileout && nMaxDebugFileSize > 0 && !fRollDisabled) | ||
| 421 | { | ||
| 422 | // Roll an overgrown debug.log before adding to it. Nothing in the | ||
| 423 | // tree shrinks this file once the process is running (there is no | ||
| 424 | // ShrinkDebugFile, and even Bitcoin's only ran at startup), so a | ||
| 425 | // node that stays up for months grows the log without bound -- | ||
| 426 | // production hit ~2 GiB. The file is opened and closed per line, | ||
| 427 | // so a rename is safe here: the next line simply reopens the | ||
| 428 | // path. One generation is kept as debug.log.old; logrotate | ||
| 429 | // (contrib/logrotate/) handles anything longer-term. | ||
| 430 | int64 nSize = GetFilesize(fileout); | ||
| 431 | if (nSize >= 0 && nSize > nMaxDebugFileSize) | ||
| 432 | { | ||
| 433 | fclose(fileout); | ||
| 434 | string strOldFile = strDebugFile + ".old"; | ||
| 435 | remove(strOldFile.c_str()); // rename() won't clobber on Windows | ||
| 436 | bool fRolled = (rename(strDebugFile.c_str(), strOldFile.c_str()) == 0); | ||
| 437 | int nRenameErrno = errno; // before fopen() can overwrite it | ||
| 438 | fileout = fopen(strDebugFile.c_str(), "a"); | ||
| 439 | if (fRolled) | ||
| 440 | { | ||
| 441 | if (fileout) | ||
| 442 | fprintf(fileout, | ||
| 443 | "debug.log grew past %lld MB; previous contents moved to debug.log.old (-maxdebugfilesize)\n", | ||
| 444 | (long long)(nMaxDebugFileSize / 1024 / 1024)); | ||
| 445 | } | ||
| 446 | else if (nRenameErrno == ENOENT) | ||
| 447 | { | ||
| 448 | // The file went away between the size check and the | ||
| 449 | // rename, so an external rotator (logrotate) got there | ||
| 450 | // first. Nothing left to roll and nothing wrong: the | ||
| 451 | // fopen above has already recreated it. Latching on this | ||
| 452 | // would let a benign race with logrotate switch the cap | ||
| 453 | // off for the rest of the run. | ||
| 454 | } | ||
| 455 | else | ||
| 456 | { | ||
| 457 | // The file is still over the cap, so this branch would be | ||
| 458 | // reached again on the next line and every line after it. | ||
| 459 | // Unlatched, the complaint about failing to roll becomes | ||
| 460 | // the runaway growth the roll exists to prevent. Say it | ||
| 461 | // once and stop trying -- on stderr too, because whatever | ||
| 462 | // blocked the rename (read-only mount, permissions, EXDEV | ||
| 463 | // across a bind mount) may equally block the log write. | ||
| 464 | fRollDisabled = true; | ||
| 465 | fprintf(stderr, | ||
| 466 | "cannot roll %s (rename to .old failed: %s); -maxdebugfilesize disabled for this run\n", | ||
| 467 | strDebugFile.c_str(), strerror(nRenameErrno)); | ||
| 468 | if (fileout) | ||
| 469 | fprintf(fileout, | ||
| 470 | "cannot roll debug.log (rename to .old failed: %s); -maxdebugfilesize disabled for this run\n", | ||
| 471 | strerror(nRenameErrno)); | ||
| 472 | } | ||
| 473 | } | ||
| 474 | } | ||
| 408 | if (fileout) | 475 | if (fileout) |
| 409 | { | 476 | { |
| 410 | va_list arg_ptr; | 477 | va_list arg_ptr; |