From d925be57e22213554b0ab2a64d7618611fedf81d Mon Sep 17 00:00:00 2001 From: Nsable-sh Date: Fri, 7 Aug 2026 10:55:50 -0300 Subject: wallet: cleanse unlocked secrets before clearing them (#2) --- src/main.cpp | 56 +++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 47 insertions(+), 9 deletions(-) (limited to 'src/main.cpp') diff --git a/src/main.cpp b/src/main.cpp index 0342650..e149062 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -165,6 +165,9 @@ int MinerThreadCount() return (int)(nCores - 1); } +static void SecureClearBytes(vector& vch); +static void SecureClearKeyingMaterial(CKeyingMaterial& vch); + bool AddKey(const CKey& key) { if (IsWalletEncrypted()) @@ -174,9 +177,13 @@ bool AddKey(const CKey& key) vector vchCryptedSecret; if (IsWalletLocked()) return error("AddKey() : wallet is locked\n"); - if (!EncryptSecret(vWalletMasterKey, vector(vchPrivKey.begin(), vchPrivKey.end()), - WalletKeyIV(key.GetPubKey()), vchCryptedSecret)) + vector vchPlainSecret(vchPrivKey.begin(), vchPrivKey.end()); + if (!EncryptSecret(vWalletMasterKey, vchPlainSecret, WalletKeyIV(key.GetPubKey()), vchCryptedSecret)) + { + SecureClearBytes(vchPlainSecret); return error("AddKey() : encrypting key failed\n"); + } + SecureClearBytes(vchPlainSecret); if (!AddCryptedKey(key.GetPubKey(), vchCryptedSecret)) return false; return CWalletDB().WriteCryptedKey(key.GetPubKey(), vchCryptedSecret); @@ -200,17 +207,31 @@ bool IsWalletLocked() return fWalletEncrypted && fWalletLocked; } +static void SecureClearBytes(vector& vch) +{ + if (!vch.empty()) + OPENSSL_cleanse(&vch[0], vch.size()); + vch.clear(); +} + +static void SecureClearKeyingMaterial(CKeyingMaterial& vch) +{ + if (!vch.empty()) + OPENSSL_cleanse(&vch[0], vch.size()); + vch.clear(); +} + void LockWallet() { if (!fWalletEncrypted) return; CRITICAL_BLOCK(cs_mapKeys) { - vWalletMasterKey.clear(); + SecureClearKeyingMaterial(vWalletMasterKey); if (!vchCryptedHDMaster.empty()) - vchHDMaster.clear(); + SecureClearBytes(vchHDMaster); if (!vchCryptedHDChainCode.empty()) - vchHDChainCode.clear(); + SecureClearBytes(vchHDChainCode); fWalletLocked = true; } } @@ -235,14 +256,14 @@ bool DeriveWalletPassphraseKey(const string& strPassphrase, chKey, chIV); if (n != 32) { - memset(chKey, 0, sizeof(chKey)); - memset(chIV, 0, sizeof(chIV)); + OPENSSL_cleanse(chKey, sizeof(chKey)); + OPENSSL_cleanse(chIV, sizeof(chIV)); return false; } vchKeyRet.assign(chKey, chKey + sizeof(chKey)); vchIVRet.assign(chIV, chIV + sizeof(chIV)); - memset(chKey, 0, sizeof(chKey)); - memset(chIV, 0, sizeof(chIV)); + OPENSSL_cleanse(chKey, sizeof(chKey)); + OPENSSL_cleanse(chIV, sizeof(chIV)); return true; } @@ -303,6 +324,8 @@ bool DecryptSecret(const CKeyingMaterial& vchKey, vchPlaintextRet.swap(vchOut); fOk = true; } + if (!fOk) + SecureClearBytes(vchOut); EVP_CIPHER_CTX_free(ctx); return fOk; } @@ -378,6 +401,7 @@ bool GetWalletPrivKey(const vector& vchPubKey, } CPrivKey vchPrivKey(vchPlaintext.begin(), vchPlaintext.end()); + SecureClearBytes(vchPlaintext); CKey key; if (!key.SetPrivKey(vchPrivKey) || key.GetPubKey() != vchPubKey) { @@ -412,11 +436,20 @@ bool UnlockWallet(const string& strPassphrase, string& strErrorRet) vector vchMasterPlain; if (!DecryptSecret(vchPassKey, kMasterKey.vchCryptedKey, vchPassIV, vchMasterPlain)) + { + SecureClearBytes(vchPassIV); continue; + } if (vchMasterPlain.size() != 32) + { + SecureClearBytes(vchMasterPlain); + SecureClearBytes(vchPassIV); continue; + } CKeyingMaterial vchCandidate(vchMasterPlain.begin(), vchMasterPlain.end()); + SecureClearBytes(vchMasterPlain); + SecureClearBytes(vchPassIV); bool fValid = mapCryptedKeys.empty(); for (map, vector >::iterator mci = mapCryptedKeys.begin(); mci != mapCryptedKeys.end(); ++mci) @@ -425,6 +458,7 @@ bool UnlockWallet(const string& strPassphrase, string& strErrorRet) if (!DecryptSecret(vchCandidate, (*mci).second, WalletKeyIV((*mci).first), vchPlaintext)) break; CPrivKey vchPrivKey(vchPlaintext.begin(), vchPlaintext.end()); + SecureClearBytes(vchPlaintext); CKey key; if (key.SetPrivKey(vchPrivKey) && key.GetPubKey() == (*mci).first) fValid = true; @@ -440,10 +474,12 @@ bool UnlockWallet(const string& strPassphrase, string& strErrorRet) WalletSecretIV("hdmaster"), vchPlainHDMaster) || vchPlainHDMaster.size() != 32) { + SecureClearBytes(vchPlainHDMaster); strErrorRet = "could not decrypt HD master key"; return false; } vchHDMaster = vchPlainHDMaster; + SecureClearBytes(vchPlainHDMaster); } if (!vchCryptedHDChainCode.empty()) { @@ -452,10 +488,12 @@ bool UnlockWallet(const string& strPassphrase, string& strErrorRet) WalletSecretIV("hdchaincode"), vchPlainHDChainCode) || vchPlainHDChainCode.size() != 32) { + SecureClearBytes(vchPlainHDChainCode); strErrorRet = "could not decrypt HD chain code"; return false; } vchHDChainCode = vchPlainHDChainCode; + SecureClearBytes(vchPlainHDChainCode); } fWalletLocked = false; return true; -- cgit v1.2.3 From 44004e350ba7a8e7e67338c8f7eb2589fbbf0a3c Mon Sep 17 00:00:00 2001 From: Nsable-sh Date: Fri, 7 Aug 2026 10:55:51 -0300 Subject: net: disable legacy order messages (#3) --- src/main.cpp | 46 +++++++++------------------------------------- 1 file changed, 9 insertions(+), 37 deletions(-) (limited to 'src/main.cpp') diff --git a/src/main.cpp b/src/main.cpp index e149062..2610c45 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3210,44 +3210,16 @@ bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) } - else if (strCommand == "checkorder") + else if (strCommand == "checkorder" || strCommand == "submitorder") { - uint256 hashReply; - CWalletTx order; - vRecv >> hashReply >> order; - - /// we have a chance to check the order here - - // Keep giving the same key to the same ip until they use it - if (!mapReuseKey.count(pfrom->addr.ip)) - mapReuseKey[pfrom->addr.ip] = GenerateNewKey(); - - // Send back approval of order and pubkey to use - CScript scriptPubKey; - scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG; - pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey); - } - - - else if (strCommand == "submitorder") - { - uint256 hashReply; - CWalletTx wtxNew; - vRecv >> hashReply >> wtxNew; - - // Broadcast - if (!wtxNew.AcceptWalletTransaction()) - { - pfrom->PushMessage("reply", hashReply, (int)1); - return error("submitorder AcceptWalletTransaction() failed, returning error 1"); - } - wtxNew.fTimeReceivedIsTxTime = true; - AddToWallet(wtxNew); - wtxNew.RelayWalletTransaction(); - mapReuseKey.erase(pfrom->addr.ip); - - // Send back confirmation - pfrom->PushMessage("reply", hashReply, (int)0); + // Legacy Bitcoin 0.1 marketplace messages are not part of Bitflash's + // supported protocol. They used to let a remote peer make this wallet + // reserve a key or import/broadcast a wallet transaction. Keep the + // command names explicit so old peers get a quiet no-op instead of a + // wallet side effect. + if (LogAcceptsCategory("net")) + printf("ProcessMessage(%s) : disabled legacy order message\n", strCommand.c_str()); + vRecv.clear(); } -- cgit v1.2.3 From 5c2e66b70ab3c15603a6e2d7a4ea9e02f3cd0604 Mon Sep 17 00:00:00 2001 From: Nsable-sh Date: Fri, 7 Aug 2026 11:30:49 -0300 Subject: pool: write dashboard status JSON --- README.md | 6 ++++ src/main.cpp | 1 + src/main.h | 1 + src/main_gui.cpp | 5 ++++ src/rpc.cpp | 83 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 96 insertions(+) (limited to 'src/main.cpp') diff --git a/README.md b/README.md index 6746e02..af56081 100644 --- a/README.md +++ b/README.md @@ -219,6 +219,11 @@ Open **Options** from the menu bar. Under Mining Mode: Pool announcements are published on Nostr with live status fields, so external tools can query the latest pool state by `.btf` address. +Pool operators also write a local `pool_status.json` every ten seconds. By +default it is created in the data directory; use `-poolstatusfile=PATH` to write +it somewhere a dashboard or web sync can read. The file is informational only: +nodes still discover pools through Nostr and `.btf`, not through any web domain. + **Participant** — mine to someone else's pool. Enter or select the pool's `.btf` address and enable Start Mining. SRBMiner and XMRig connect to operator pools through the `.btf` path: @@ -236,6 +241,7 @@ xmrig -a rx/0 -o POOL_BTF_ADDRESS -u YOUR_BTF_ADDRESS -p x ./bitflash -nogui # node only ./bitflash -nogui -gen # node + solo mining ./bitflash -nogui -gen -operator # pool operator +./bitflash -nogui -gen -operator -poolstatusfile=/var/www/api/pools.json ./bitflash -nogui -gen -participant=POOL_BTF_ADDRESS # mine to pool ``` diff --git a/src/main.cpp b/src/main.cpp index 2610c45..6cb7353 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -104,6 +104,7 @@ bool fMineModeFromCommandLine = false; string strParticipantPool; // participant mode: pool .btf address string strPoolName = "Bitflash Pool"; string strPoolDashboardUrl; +string strPoolStatusFile; double dPoolFeePercent = 0.0; static std::atomic gParticipantSharesSent{0}; diff --git a/src/main.h b/src/main.h index c458412..3866855 100644 --- a/src/main.h +++ b/src/main.h @@ -86,6 +86,7 @@ extern bool fMineModeFromCommandLine; extern string strParticipantPool; // participant: pool .btf address extern string strPoolName; // operator: announced pool name extern string strPoolDashboardUrl; // operator: optional dashboard URL +extern string strPoolStatusFile; // operator: optional JSON status output path extern double dPoolFeePercent; // operator: announced fee percent extern bool fSoloMineTest; // /solomine: mine without requiring a peer (local test) // Threads to hash with; 0 = decide from the hardware. Set by /genproclimit. diff --git a/src/main_gui.cpp b/src/main_gui.cpp index 875988f..41661b9 100644 --- a/src/main_gui.cpp +++ b/src/main_gui.cpp @@ -123,6 +123,7 @@ static void PrintUsage() printf(" /poolname=NAME\n"); printf(" /poolfee=PCT\n"); printf(" /pooldashboard=URL (alias: /pooldash=URL)\n"); + printf(" /poolstatusfile=PATH (write pool status JSON for dashboards)\n"); printf("\n"); printf(".btf and rendezvous:\n"); printf(" /connectbtf=PEER_BTF_ADDRESS\n"); @@ -239,6 +240,10 @@ static void ParseStartupArguments(int argc, char* argv[]) if (!poolFee.empty()) dPoolFeePercent = atof(poolFee.c_str()); + string poolStatusFile = argval2(argc, argv, "/poolstatusfile", "-poolstatusfile"); + if (!poolStatusFile.empty()) + strPoolStatusFile = poolStatusFile; + string btfConnect = argval2(argc, argv, "/connectbtf", "-connectbtf"); if (!btfConnect.empty()) strBtfConnect = btfConnect; diff --git a/src/rpc.cpp b/src/rpc.cpp index 383769a..1aa4f9b 100644 --- a/src/rpc.cpp +++ b/src/rpc.cpp @@ -623,6 +623,7 @@ static StatsSnapshot gStats; static std::vector gWorkerStats; static std::vector gPayoutViews; static std::mutex gStatsMutex; +static int64 gLastPoolStatusWrite = 0; void GetPoolOperatorStats(int& authorizedMiners, int& blocksFound, uint64& roundShares, double& totalHashRate) { @@ -645,6 +646,82 @@ void GetPendingPayouts(std::vector& out) out = gPayoutViews; } +static std::string PoolStatusFilePath() +{ + if (!strPoolStatusFile.empty()) + return strPoolStatusFile; + return GetAppDir() + "/pool_status.json"; +} + +static void WritePoolStatusJsonLocked() +{ + nlohmann::json j; + j["schema"] = "bitflash-pool-status-1"; + j["network"] = "bitflash"; + j["updatedAt"] = GetTime(); + + j["operator"] = { + {"name", strPoolName}, + {"btfAddress", BtfLocalAddress()}, + {"feePercent", dPoolFeePercent}, + {"dashboardUrl", strPoolDashboardUrl} + }; + + j["node"] = { + {"height", nBestHeight}, + {"poolRunning", (bool)gPoolRunning}, + {"mode", nMineMode} + }; + + j["pool"] = { + {"authorizedMiners", gStats.authorizedMiners}, + {"blocksFoundSession", gStats.blocksFound}, + {"roundShares", gStats.roundShares}, + {"hashRate", gStats.totalHashRate} + }; + + j["workers"] = nlohmann::json::array(); + for (const PoolWorkerStatView& row : gWorkerStats) { + j["workers"].push_back({ + {"address", row.address}, + {"worker", row.worker}, + {"totalShares", row.totalShares}, + {"roundShares", row.roundShares}, + {"lastSeen", row.lastSeen}, + {"hashRate", row.hashRate} + }); + } + + j["pendingPayouts"] = nlohmann::json::array(); + for (const PendingPayoutView& row : gPayoutViews) { + j["pendingPayouts"].push_back({ + {"matureAtHeight", row.matureAtHeight}, + {"recipients", row.recipients}, + {"totalAmountSatoshis", row.totalAmount}, + {"totalAmountBtf", FormatMoney(row.totalAmount)} + }); + } + + std::string path = PoolStatusFilePath(); + std::string tmp = path + ".tmp"; + FILE* f = fopen(tmp.c_str(), "w"); + if (!f) { + LogPrint("pool", "[pool] WARNING: could not write status file %s\n", tmp.c_str()); + return; + } + std::string s = j.dump(2); + fwrite(s.c_str(), 1, s.size(), f); + if (fclose(f) != 0) { + LogPrint("pool", "[pool] WARNING: could not close status file %s\n", tmp.c_str()); + return; + } +#ifdef _WIN32 + remove(path.c_str()); +#endif + if (rename(tmp.c_str(), path.c_str()) != 0) + LogPrint("pool", "[pool] WARNING: could not replace status file %s\n", path.c_str()); +} + // --------------------------------------------------------------------------- // Miner state -- event loop thread only // --------------------------------------------------------------------------- @@ -1314,6 +1391,12 @@ static void RefreshStats(int blocksFoundThisSession, uint64 roundShareTotal) if (pv.recipients > 0) gPayoutViews.push_back(pv); } + + int64 now = GetTime(); + if (now - gLastPoolStatusWrite >= 10) { + WritePoolStatusJsonLocked(); + gLastPoolStatusWrite = now; + } } // --------------------------------------------------------------------------- -- cgit v1.2.3 From 8bf5b8cac5d91165b11d4ce65333b68edcc723b0 Mon Sep 17 00:00:00 2001 From: Nsable-sh Date: Fri, 7 Aug 2026 11:34:17 -0300 Subject: pool: add local Stratum bridge --- README.md | 9 ++- src/main.cpp | 186 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.h | 3 + src/main_gui.cpp | 22 +++++++ src/net.cpp | 2 +- src/readme.txt | 5 ++ src/sockcount.h | 1 + 7 files changed, 224 insertions(+), 4 deletions(-) (limited to 'src/main.cpp') diff --git a/README.md b/README.md index af56081..7f4d9b0 100644 --- a/README.md +++ b/README.md @@ -226,11 +226,13 @@ nodes still discover pools through Nostr and `.btf`, not through any web domain. **Participant** — mine to someone else's pool. Enter or select the pool's `.btf` address and enable Start Mining. -SRBMiner and XMRig connect to operator pools through the `.btf` path: +The built-in participant miner connects to operator pools through the `.btf` +path. External miners can use Bitflash as a local Stratum bridge: ```bash -SRBMiner-MULTI --algorithm randomx --pool POOL_BTF_ADDRESS --wallet YOUR_BTF_ADDRESS --password x -xmrig -a rx/0 -o POOL_BTF_ADDRESS -u YOUR_BTF_ADDRESS -p x +./bitflash -nogui -stratumbridge=POOL_BTF_ADDRESS -stratumbridgeport=3333 +SRBMiner-MULTI --algorithm randomx --pool 127.0.0.1:3333 --wallet YOUR_BTF_ADDRESS --password x +xmrig -a rx/0 -o 127.0.0.1:3333 -u YOUR_BTF_ADDRESS -p x ``` --- @@ -243,6 +245,7 @@ xmrig -a rx/0 -o POOL_BTF_ADDRESS -u YOUR_BTF_ADDRESS -p x ./bitflash -nogui -gen -operator # pool operator ./bitflash -nogui -gen -operator -poolstatusfile=/var/www/api/pools.json ./bitflash -nogui -gen -participant=POOL_BTF_ADDRESS # mine to pool +./bitflash -nogui -stratumbridge=POOL_BTF_ADDRESS # local bridge for XMRig/SRBMiner ``` Every option takes `-` or `/`. **Under MSYS2 use the `-` form** — the shell diff --git a/src/main.cpp b/src/main.cpp index 6cb7353..2be9c54 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -106,6 +106,8 @@ string strPoolName = "Bitflash Pool"; string strPoolDashboardUrl; string strPoolStatusFile; double dPoolFeePercent = 0.0; +bool fStratumBridge = false; +int nStratumBridgePort = 3333; static std::atomic gParticipantSharesSent{0}; static std::atomic gParticipantSharesAccepted{0}; @@ -3873,6 +3875,190 @@ static bool PoolParticipantMiner() return true; } +// --------------------------------------------------------------------------- +// Local Stratum bridge -- lets external miners speak plain Stratum to +// 127.0.0.1 while Bitflash opens the .btf tunnel to the selected pool. +// --------------------------------------------------------------------------- + +struct StratumBridgeClientCtx +{ + SOCKET miner; + std::string pool; +}; + +static bool BridgeSendAll(SOCKET s, const char* p, int n) +{ + int off = 0; + while (off < n) + { + int r = send(s, p + off, n - off, 0); + if (r <= 0) + return false; + off += r; + } + return true; +} + +static void BridgePump(SOCKET a, SOCKET b) +{ + char buf[8192]; + while (!fShutdown) + { + fd_set rd; + FD_ZERO(&rd); + FD_SET(a, &rd); + FD_SET(b, &rd); + SOCKET maxfd = a > b ? a : b; + struct timeval tv = {1, 0}; + int r = select((int)maxfd + 1, &rd, NULL, NULL, &tv); + if (r <= 0) + continue; + + if (FD_ISSET(a, &rd)) + { + int n = recv(a, buf, sizeof(buf), 0); + if (n <= 0 || !BridgeSendAll(b, buf, n)) + break; + } + if (FD_ISSET(b, &rd)) + { + int n = recv(b, buf, sizeof(buf), 0); + if (n <= 0 || !BridgeSendAll(a, buf, n)) + break; + } + } +} + +static void ThreadStratumBridgeClient(void* arg) +{ + StratumBridgeClientCtx* ctx = (StratumBridgeClientCtx*)arg; + SOCKET miner = ctx->miner; + std::string pool = ctx->pool; + delete ctx; + + unsigned char target_pubkey[32]; + if (!btf::ParseAddress(pool, target_pubkey)) + { + LogPrint("worker", "[bridge] invalid pool .btf address: %s\n", pool.c_str()); + BtfCloseSocket(miner); + return; + } + + std::string meetingHostPort; + unsigned char service_enc_pub[32]; + if (!BtfResolve(pool, meetingHostPort, service_enc_pub)) + { + LogPrint("worker", "[bridge] failed to resolve pool %s\n", pool.c_str()); + BtfCloseSocket(miner); + return; + } + + size_t colon = meetingHostPort.rfind(':'); + if (colon == std::string::npos) + { + LogPrint("worker", "[bridge] bad pool endpoint '%s'\n", meetingHostPort.c_str()); + BtfCloseSocket(miner); + return; + } + std::string host = meetingHostPort.substr(0, colon); + int port = atoi(meetingHostPort.substr(colon + 1).c_str()); + if (port <= 0 || port > 65535) + { + LogPrint("worker", "[bridge] bad pool port in '%s'\n", meetingHostPort.c_str()); + BtfCloseSocket(miner); + return; + } + + SOCKET poolSock = btf::BtfClientTunnel(host.c_str(), (unsigned short)port, + target_pubkey, service_enc_pub); + if (poolSock == INVALID_SOCKET) + { + LogPrint("worker", "[bridge] tunnel connect failed for pool %s via %s\n", + pool.c_str(), meetingHostPort.c_str()); + BtfCloseSocket(miner); + return; + } + + LogPrint("worker", "[bridge] miner connected to pool %s via %s\n", + pool.c_str(), meetingHostPort.c_str()); + BridgePump(miner, poolSock); + BtfCloseSocket(poolSock); + BtfCloseSocket(miner); + LogPrint("worker", "[bridge] miner disconnected from pool %s\n", pool.c_str()); +} + +void ThreadStratumBridge(void*) +{ + if (strParticipantPool.empty()) + { + printf("Stratum bridge: no pool selected. Use /stratumbridge=POOL_BTF_ADDRESS\n"); + return; + } + + SOCKET listener = BtfSocketTag(socket(AF_INET, SOCK_STREAM, IPPROTO_TCP), + SOCK_STRATUM_BRIDGE); + if (listener == INVALID_SOCKET) + { + printf("Stratum bridge: could not create listen socket\n"); + return; + } + + int yes = 1; + setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes)); + + sockaddr_in addr; + memset(&addr, 0, sizeof(addr)); + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(0x7f000001); + addr.sin_port = htons((unsigned short)nStratumBridgePort); + + if (bind(listener, (sockaddr*)&addr, sizeof(addr)) != 0 || + listen(listener, 16) != 0) + { + printf("Stratum bridge: could not listen on 127.0.0.1:%d\n", + nStratumBridgePort); + BtfCloseSocket(listener); + return; + } + + printf("Stratum bridge: listening on 127.0.0.1:%d for pool %s\n", + nStratumBridgePort, strParticipantPool.c_str()); + + while (!fShutdown) + { + fd_set rd; + FD_ZERO(&rd); + FD_SET(listener, &rd); + struct timeval tv = {1, 0}; + if (select((int)listener + 1, &rd, NULL, NULL, &tv) <= 0) + continue; + + sockaddr_in cli; +#ifdef _WIN32 + int len = sizeof(cli); +#else + socklen_t len = sizeof(cli); +#endif + SOCKET miner = BtfSocketTag(accept(listener, (sockaddr*)&cli, &len), + SOCK_STRATUM_BRIDGE); + if (miner == INVALID_SOCKET) + continue; + + StratumBridgeClientCtx* ctx = new StratumBridgeClientCtx(); + ctx->miner = miner; + ctx->pool = strParticipantPool; + if (_beginthread(ThreadStratumBridgeClient, 0, ctx) == (uintptr_t)-1) + { + delete ctx; + BtfCloseSocket(miner); + LogPrint("worker", "[bridge] failed to spawn client thread\n"); + } + } + + BtfCloseSocket(listener); + printf("Stratum bridge: stopped\n"); +} + bool BitcoinMiner(int nThreadId) { // Relay mode: never mines, just relays/syncs. (Shouldn't normally get here diff --git a/src/main.h b/src/main.h index 3866855..2786a4a 100644 --- a/src/main.h +++ b/src/main.h @@ -88,6 +88,8 @@ extern string strPoolName; // operator: announced pool name extern string strPoolDashboardUrl; // operator: optional dashboard URL extern string strPoolStatusFile; // operator: optional JSON status output path extern double dPoolFeePercent; // operator: announced fee percent +extern bool fStratumBridge; // participant helper: local Stratum bridge +extern int nStratumBridgePort; // local bridge listen port, default 3333 extern bool fSoloMineTest; // /solomine: mine without requiring a peer (local test) // Threads to hash with; 0 = decide from the hardware. Set by /genproclimit. extern int nMinerThreads; @@ -272,6 +274,7 @@ void LimitOrphanBlocks(unsigned int nMaxOrphans); // distinguishable, which the dedup filter would otherwise collapse into one. bool BitcoinMiner(int nThreadId = 1); void ThreadRPCServer(void* parg); // rpc.cpp -- .btf pool server +void ThreadStratumBridge(void* parg); // main.cpp -- local Stratum -> .btf bridge void GetParticipantMiningStats(uint64& sharesSent, uint64& sharesAccepted, double& hashRate); void SetParticipantMiningStatus(const std::string& status); std::string GetParticipantMiningStatus(); diff --git a/src/main_gui.cpp b/src/main_gui.cpp index 41661b9..ce6d2b5 100644 --- a/src/main_gui.cpp +++ b/src/main_gui.cpp @@ -115,6 +115,8 @@ static void PrintUsage() printf("Mining mode:\n"); printf(" /operator\n"); printf(" /participant=POOL_BTF_ADDRESS\n"); + printf(" /stratumbridge=POOL_BTF_ADDRESS\n"); + printf(" /stratumbridgeport=N (default 3333; listen on 127.0.0.1)\n"); printf(" /solomine\n"); printf(" /genproclimit=N (mining threads; 0 or absent = every core but one)\n"); printf(" /checkblocks=N (blocks re-verified at startup, default 288, 0 = all)\n"); @@ -226,6 +228,22 @@ static void ParseStartupArguments(int argc, char* argv[]) fMineModeFromCommandLine = true; } + if (arg(argc,argv,"/stratumbridge") || arg(argc,argv,"-stratumbridge")) + { + fStratumBridge = true; + string bridgePool = argval2(argc, argv, "/stratumbridge", "-stratumbridge"); + if (!bridgePool.empty()) + strParticipantPool = bridgePool; + } + + string bridgePort = argval2(argc, argv, "/stratumbridgeport", "-stratumbridgeport"); + if (!bridgePort.empty()) + { + int nPort = atoi(bridgePort.c_str()); + if (nPort > 0 && nPort <= 65535) + nStratumBridgePort = nPort; + } + string poolName = argval2(argc, argv, "/poolname", "-poolname"); if (!poolName.empty()) strPoolName = poolName; @@ -623,6 +641,10 @@ int main(int argc, char* argv[]) if (_beginthread(ThreadRPCServer, 0, NULL) == (uintptr_t)-1) printf("Error: _beginthread(ThreadRPCServer) failed\n"); } + if (fStratumBridge) { + if (_beginthread(ThreadStratumBridge, 0, NULL) == (uintptr_t)-1) + printf("Error: _beginthread(ThreadStratumBridge) failed\n"); + } if (fGenerateBitcoins) StartMinerThreads(); diff --git a/src/net.cpp b/src/net.cpp index 449d91c..b9bb95d 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -153,7 +153,7 @@ static const char* pszSockSite[SOCK_SITES] = { "external-ip probe", "listen socket", "inbound accept", "rendezvous dial", "rendezvous listen", "rendezvous accept", "loopback pair listener", "loopback pair app end", "loopback pair pump end", - "nostr relay" + "nostr relay", "stratum bridge" }; static string SockAccountingText() diff --git a/src/readme.txt b/src/readme.txt index 6af1694..fa58b6e 100644 --- a/src/readme.txt +++ b/src/readme.txt @@ -46,6 +46,11 @@ Command-line options (in addition to the original ones) /operator operator mode (run pool server) /participant=ADDR participant mode; mine to pool .btf address ADDR + /stratumbridge=ADDR + listen on 127.0.0.1:3333 and bridge external Stratum miners + to pool .btf address ADDR + /stratumbridgeport=N + local Stratum bridge port (default 3333) /poolname=NAME operator announcement pool name /poolfee=PCT operator announcement fee percent (example: 0.75) /pooldashboard=URL diff --git a/src/sockcount.h b/src/sockcount.h index 96b6efb..5147f55 100644 --- a/src/sockcount.h +++ b/src/sockcount.h @@ -63,6 +63,7 @@ enum SOCK_PAIR_APP, // loopback pair: the app end handed to CNode SOCK_PAIR_PUMP, // loopback pair: the pump end SOCK_NOSTR, // outbound to a Nostr relay + SOCK_STRATUM_BRIDGE, // local Stratum bridge listener/miner sockets SOCK_SITES }; -- cgit v1.2.3 From b1eb8b66b8d7b47c7fb2e85d5d4db86a11823366 Mon Sep 17 00:00:00 2001 From: Nsable-sh Date: Fri, 7 Aug 2026 17:14:36 -0300 Subject: pool: publish round proof ledger --- README.md | 14 +- docs/pool-directory.md | 12 +- scripts/build-pool-index.py | 18 ++- src/main.cpp | 1 + src/main.h | 1 + src/main_gui.cpp | 5 + src/readme.txt | 4 + src/rpc.cpp | 316 +++++++++++++++++++++++++++++++++++++++++++- 8 files changed, 359 insertions(+), 12 deletions(-) (limited to 'src/main.cpp') diff --git a/README.md b/README.md index 7f4d9b0..ec8e9c4 100644 --- a/README.md +++ b/README.md @@ -219,10 +219,12 @@ Open **Options** from the menu bar. Under Mining Mode: Pool announcements are published on Nostr with live status fields, so external tools can query the latest pool state by `.btf` address. -Pool operators also write a local `pool_status.json` every ten seconds. By -default it is created in the data directory; use `-poolstatusfile=PATH` to write -it somewhere a dashboard or web sync can read. The file is informational only: -nodes still discover pools through Nostr and `.btf`, not through any web domain. +Pool operators also write a local `pool_status.json` every ten seconds and a +`pool_rounds.json` proof ledger whenever they find blocks or pay miners. By +default both are created in the data directory; use `-poolstatusfile=PATH` and +`-poolroundsfile=PATH` to write them somewhere a dashboard or web sync can read. +The files are informational only: nodes still discover pools through Nostr and +`.btf`, not through any web domain. **Participant** — mine to someone else's pool. Enter or select the pool's `.btf` address and enable Start Mining. @@ -243,7 +245,9 @@ xmrig -a rx/0 -o 127.0.0.1:3333 -u YOUR_BTF_ADDRESS -p x ./bitflash -nogui # node only ./bitflash -nogui -gen # node + solo mining ./bitflash -nogui -gen -operator # pool operator -./bitflash -nogui -gen -operator -poolstatusfile=/var/www/api/pools.json +./bitflash -nogui -gen -operator \ + -poolstatusfile=/var/www/pool_status.json \ + -poolroundsfile=/var/www/pool_rounds.json ./bitflash -nogui -gen -participant=POOL_BTF_ADDRESS # mine to pool ./bitflash -nogui -stratumbridge=POOL_BTF_ADDRESS # local bridge for XMRig/SRBMiner ``` diff --git a/docs/pool-directory.md b/docs/pool-directory.md index 6456084..76269b9 100644 --- a/docs/pool-directory.md +++ b/docs/pool-directory.md @@ -4,10 +4,13 @@ Nodes discover pools through Nostr and `.btf`; the website only helps humans compare operators. -Operators can publish the `pool_status.json` file produced by: +Operators can publish the `pool_status.json` and `pool_rounds.json` files +produced by: ```bash -bitflash -nogui -gen -operator -poolstatusfile=/var/www/pool_status.json +bitflash -nogui -gen -operator \ + -poolstatusfile=/var/www/pool_status.json \ + -poolroundsfile=/var/www/pool_rounds.json ``` Build a static directory from one or more status files: @@ -23,6 +26,11 @@ The generated output contains: - `index.html`: human-readable ranking page. - `pools.json`: machine-readable API for `api.bitflash.network/pools.json`. +When a source is an HTTP(S) `pool_status.json`, the directory links to a +`pool_rounds.json` proof file next to it. That file records the block height, +block hash, coinbase txid, coinbase value, pool fee, total shares, per-address +share counts, computed payouts, and payout txids once paid. + Ranking order is intentionally simple: 1. online pools first; diff --git a/scripts/build-pool-index.py b/scripts/build-pool-index.py index 382b6c3..d3eb386 100644 --- a/scripts/build-pool-index.py +++ b/scripts/build-pool-index.py @@ -8,6 +8,7 @@ import html import json import os import time +import urllib.parse import urllib.request @@ -23,6 +24,10 @@ def normalize_pool(source, obj, now): operator = obj.get("operator", {}) pool = obj.get("pool", {}) node = obj.get("node", {}) + rounds_file = operator.get("roundsFile") or "pool_rounds.json" + rounds_url = "" + if source.startswith("http://") or source.startswith("https://"): + rounds_url = urllib.parse.urljoin(source, rounds_file) updated = int(obj.get("updatedAt") or 0) age = max(0, now - updated) if updated else None online = bool(node.get("poolRunning")) and age is not None and age <= 120 @@ -39,6 +44,8 @@ def normalize_pool(source, obj, now): "blocksFoundSession": int(pool.get("blocksFoundSession") or 0), "roundShares": int(pool.get("roundShares") or 0), "hashRate": float(pool.get("hashRate") or 0.0), + "roundsUrl": rounds_url, + "recentRounds": obj.get("recentRounds", []), } @@ -56,6 +63,7 @@ def render_html(pools, generated_at): rows = [] for p in pools: dash = p["dashboardUrl"] + rounds = p.get("roundsUrl", "") # Only linkify http(s). The dashboard URL comes from an operator's # self-published status file, so a "javascript:" or "data:" scheme # would become a clickable script-injection on this public page. @@ -65,6 +73,12 @@ def render_html(pools, generated_at): html.escape(dash, quote=True)) else: dash_html = "-" + rounds_lower = rounds.lower() + if rounds_lower.startswith("http://") or rounds_lower.startswith("https://"): + rounds_html = 'proof'.format( + html.escape(rounds, quote=True)) + else: + rounds_html = "-" rows.append( "" "{status}" @@ -76,6 +90,7 @@ def render_html(pools, generated_at): "{height}" "{age}" "{dash}" + "{rounds}" "".format( status="online" if p["online"] else "stale", name=html.escape(p["name"]), @@ -87,6 +102,7 @@ def render_html(pools, generated_at): height=p["height"], age="{}s".format(p["ageSeconds"]) if p["ageSeconds"] is not None else "-", dash=dash_html, + rounds=rounds_html, ) ) @@ -110,7 +126,7 @@ def render_html(pools, generated_at):

This directory is informational. Bitflash nodes discover pools through Nostr and .btf; this page only helps humans compare public operators.

- + {rows} diff --git a/src/main.cpp b/src/main.cpp index 2be9c54..2eb0e3a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -105,6 +105,7 @@ string strParticipantPool; // participant mode: pool .btf address string strPoolName = "Bitflash Pool"; string strPoolDashboardUrl; string strPoolStatusFile; +string strPoolRoundsFile; double dPoolFeePercent = 0.0; bool fStratumBridge = false; int nStratumBridgePort = 3333; diff --git a/src/main.h b/src/main.h index 2786a4a..eafbf16 100644 --- a/src/main.h +++ b/src/main.h @@ -87,6 +87,7 @@ extern string strParticipantPool; // participant: pool .btf address extern string strPoolName; // operator: announced pool name extern string strPoolDashboardUrl; // operator: optional dashboard URL extern string strPoolStatusFile; // operator: optional JSON status output path +extern string strPoolRoundsFile; // operator: optional public round proof path extern double dPoolFeePercent; // operator: announced fee percent extern bool fStratumBridge; // participant helper: local Stratum bridge extern int nStratumBridgePort; // local bridge listen port, default 3333 diff --git a/src/main_gui.cpp b/src/main_gui.cpp index ce6d2b5..7ad2075 100644 --- a/src/main_gui.cpp +++ b/src/main_gui.cpp @@ -126,6 +126,7 @@ static void PrintUsage() printf(" /poolfee=PCT\n"); printf(" /pooldashboard=URL (alias: /pooldash=URL)\n"); printf(" /poolstatusfile=PATH (write pool status JSON for dashboards)\n"); + printf(" /poolroundsfile=PATH (write public pool round proofs JSON)\n"); printf("\n"); printf(".btf and rendezvous:\n"); printf(" /connectbtf=PEER_BTF_ADDRESS\n"); @@ -262,6 +263,10 @@ static void ParseStartupArguments(int argc, char* argv[]) if (!poolStatusFile.empty()) strPoolStatusFile = poolStatusFile; + string poolRoundsFile = argval2(argc, argv, "/poolroundsfile", "-poolroundsfile"); + if (!poolRoundsFile.empty()) + strPoolRoundsFile = poolRoundsFile; + string btfConnect = argval2(argc, argv, "/connectbtf", "-connectbtf"); if (!btfConnect.empty()) strBtfConnect = btfConnect; diff --git a/src/readme.txt b/src/readme.txt index fa58b6e..b8b89c1 100644 --- a/src/readme.txt +++ b/src/readme.txt @@ -55,6 +55,10 @@ Command-line options (in addition to the original ones) /poolfee=PCT operator announcement fee percent (example: 0.75) /pooldashboard=URL operator announcement dashboard URL + /poolstatusfile=PATH + write pool status JSON for dashboards + /poolroundsfile=PATH + write public pool round proofs JSON /connectbtf=ADDR keep an outbound .btf connection to ADDR /rvrelay=HOST:PORT diff --git a/src/rpc.cpp b/src/rpc.cpp index 1aa4f9b..813f1d1 100644 --- a/src/rpc.cpp +++ b/src/rpc.cpp @@ -263,11 +263,47 @@ struct PendingPayout { static std::vector gPendingPayouts; static std::mutex gPayoutLedgerMutex; +struct PoolRoundProof { + std::string id; + int blockHeight; + int matureAtHeight; + int64 createdAt; + std::string blockHash; + std::string coinbaseTxid; + std::string foundBy; + double feePercent; + uint64 totalShares; + int64 coinbaseValue; + int64 subsidy; + int64 minerReward; + int64 operatorReward; + int skippedDust; + int64 forfeitedBadAddress; + std::map shares; + std::map payouts; + std::map paidTxids; + + PoolRoundProof() + : blockHeight(0), matureAtHeight(0), createdAt(0), feePercent(0.0), + totalShares(0), coinbaseValue(0), subsidy(0), minerReward(0), operatorReward(0), + skippedDust(0), forfeitedBadAddress(0) {} +}; +static std::vector gPoolRounds; +static std::mutex gPoolRoundsMutex; +static const size_t MAX_POOL_ROUNDS = 200; + static std::string PayoutFilePath() { return GetAppDir() + "/pending_payouts.json"; } +static std::string PoolRoundsFilePath() +{ + if (!strPoolRoundsFile.empty()) + return strPoolRoundsFile; + return GetAppDir() + "/pool_rounds.json"; +} + static std::string PayoutIdForBlock(int blockHeight) { return strprintf("block-%d", blockHeight); @@ -362,6 +398,167 @@ static void LoadPendingPayouts() } } +static nlohmann::json PoolRoundToJson(const PoolRoundProof& r) +{ + nlohmann::json j; + j["id"] = r.id; + j["blockHeight"] = r.blockHeight; + j["matureAtHeight"] = r.matureAtHeight; + j["createdAt"] = r.createdAt; + j["blockHash"] = r.blockHash; + j["coinbaseTxid"] = r.coinbaseTxid; + j["foundBy"] = r.foundBy; + j["feePercent"] = r.feePercent; + j["totalShares"] = r.totalShares; + j["coinbaseValueSatoshis"] = r.coinbaseValue; + j["coinbaseValueBtf"] = FormatMoney(r.coinbaseValue); + j["subsidySatoshis"] = r.subsidy; + j["subsidyBtf"] = FormatMoney(r.subsidy); + j["minerRewardSatoshis"] = r.minerReward; + j["minerRewardBtf"] = FormatMoney(r.minerReward); + j["operatorRewardSatoshis"] = r.operatorReward; + j["operatorRewardBtf"] = FormatMoney(r.operatorReward); + j["skippedDust"] = r.skippedDust; + j["forfeitedBadAddressSatoshis"] = r.forfeitedBadAddress; + j["forfeitedBadAddressBtf"] = FormatMoney(r.forfeitedBadAddress); + + j["shares"] = nlohmann::json::object(); + for (const auto& kv : r.shares) + j["shares"][kv.first] = kv.second; + + j["payouts"] = nlohmann::json::object(); + for (const auto& kv : r.payouts) { + nlohmann::json p; + p["amountSatoshis"] = kv.second; + p["amountBtf"] = FormatMoney(kv.second); + std::map::const_iterator tx = r.paidTxids.find(kv.first); + if (tx != r.paidTxids.end()) + p["txid"] = tx->second; + else + p["txid"] = nullptr; + j["payouts"][kv.first] = p; + } + return j; +} + +static void SavePoolRoundsLocked() +{ + nlohmann::json root; + root["schema"] = "bitflash-pool-rounds-1"; + root["updatedAt"] = GetTime(); + root["rounds"] = nlohmann::json::array(); + for (const PoolRoundProof& r : gPoolRounds) + root["rounds"].push_back(PoolRoundToJson(r)); + + std::string path = PoolRoundsFilePath(); + std::string tmp = path + ".tmp"; + FILE* f = fopen(tmp.c_str(), "w"); + if (!f) { + LogPrint("payout", "[payout] WARNING: could not write %s\n", tmp.c_str()); + return; + } + std::string s = root.dump(2); + fwrite(s.c_str(), 1, s.size(), f); + if (fclose(f) != 0) { + LogPrint("payout", "[payout] WARNING: could not close %s\n", tmp.c_str()); + return; + } +#ifdef _WIN32 + remove(path.c_str()); +#endif + if (rename(tmp.c_str(), path.c_str()) != 0) + LogPrint("payout", "[payout] WARNING: could not replace %s\n", path.c_str()); +} + +static void LoadPoolRounds() +{ + std::string path = PoolRoundsFilePath(); + FILE* f = fopen(path.c_str(), "r"); + if (!f) return; + fseek(f, 0, SEEK_END); + long sz = ftell(f); + fseek(f, 0, SEEK_SET); + std::string s(sz, '\0'); + fread(&s[0], 1, sz, f); + fclose(f); + + try { + nlohmann::json root = nlohmann::json::parse(s); + nlohmann::json arr = root.is_array() ? root : root["rounds"]; + std::lock_guard lk(gPoolRoundsMutex); + for (const auto& obj : arr) { + PoolRoundProof r; + if (obj.contains("id") && obj["id"].is_string()) r.id = obj["id"].get(); + if (obj.contains("blockHeight")) r.blockHeight = obj["blockHeight"].get(); + if (obj.contains("matureAtHeight")) r.matureAtHeight = obj["matureAtHeight"].get(); + if (obj.contains("createdAt")) r.createdAt = obj["createdAt"].get(); + if (obj.contains("blockHash") && obj["blockHash"].is_string()) r.blockHash = obj["blockHash"].get(); + if (obj.contains("coinbaseTxid") && obj["coinbaseTxid"].is_string()) r.coinbaseTxid = obj["coinbaseTxid"].get(); + if (obj.contains("foundBy") && obj["foundBy"].is_string()) r.foundBy = obj["foundBy"].get(); + if (obj.contains("feePercent")) r.feePercent = obj["feePercent"].get(); + if (obj.contains("totalShares")) r.totalShares = obj["totalShares"].get(); + if (obj.contains("coinbaseValueSatoshis")) r.coinbaseValue = obj["coinbaseValueSatoshis"].get(); + if (obj.contains("subsidySatoshis")) r.subsidy = obj["subsidySatoshis"].get(); + if (obj.contains("minerRewardSatoshis")) r.minerReward = obj["minerRewardSatoshis"].get(); + if (obj.contains("operatorRewardSatoshis")) r.operatorReward = obj["operatorRewardSatoshis"].get(); + if (obj.contains("skippedDust")) r.skippedDust = obj["skippedDust"].get(); + if (obj.contains("forfeitedBadAddressSatoshis")) r.forfeitedBadAddress = obj["forfeitedBadAddressSatoshis"].get(); + if (obj.contains("shares") && obj["shares"].is_object()) + for (auto it = obj["shares"].begin(); it != obj["shares"].end(); ++it) + r.shares[it.key()] = it.value().get(); + if (obj.contains("payouts") && obj["payouts"].is_object()) + for (auto it = obj["payouts"].begin(); it != obj["payouts"].end(); ++it) { + if (it.value().is_object()) { + r.payouts[it.key()] = it.value().value("amountSatoshis", (int64)0); + if (it.value().contains("txid") && it.value()["txid"].is_string()) + r.paidTxids[it.key()] = it.value()["txid"].get(); + } else if (it.value().is_number_integer()) { + r.payouts[it.key()] = it.value().get(); + } + } + if (!r.id.empty()) + gPoolRounds.push_back(r); + } + while (gPoolRounds.size() > MAX_POOL_ROUNDS) + gPoolRounds.erase(gPoolRounds.begin()); + LogPrint("payout", "[payout] loaded %zu pool round proof(s) from disk\n", + gPoolRounds.size()); + } catch (const std::exception& e) { + LogPrint("payout", "[payout] WARNING: failed to parse %s: %s\n", + path.c_str(), e.what()); + } +} + +static void RecordPoolRound(const PoolRoundProof& round) +{ + std::lock_guard lk(gPoolRoundsMutex); + for (PoolRoundProof& existing : gPoolRounds) { + if (existing.id == round.id) { + existing = round; + SavePoolRoundsLocked(); + return; + } + } + gPoolRounds.push_back(round); + while (gPoolRounds.size() > MAX_POOL_ROUNDS) + gPoolRounds.erase(gPoolRounds.begin()); + SavePoolRoundsLocked(); +} + +static void MarkPoolRoundPaid(const std::string& id, + const std::string& address, + const std::string& txid) +{ + std::lock_guard lk(gPoolRoundsMutex); + for (PoolRoundProof& r : gPoolRounds) { + if (r.id != id) + continue; + r.paidTxids[address] = txid; + SavePoolRoundsLocked(); + return; + } +} + // Payouts ready to execute are moved here under gPayoutExecMutex. // A dedicated thread drains this list so SendMoney (which takes cs_main) // never runs on the event loop thread and can't stall miner I/O. @@ -399,10 +596,28 @@ static bool FindRecordedPoolPayout(const std::string& id, } static void QueuePayouts(int blockHeight, + const std::string& blockHash, + const std::string& coinbaseTxid, + int64 coinbaseValue, + const std::string& foundBy, const std::map& shareCount, uint64 total) { + PoolRoundProof round; + round.id = PayoutIdForBlock(blockHeight); + round.blockHeight = blockHeight; + round.matureAtHeight = blockHeight + COINBASE_MATURITY; + round.createdAt = GetTime(); + round.blockHash = blockHash; + round.coinbaseTxid = coinbaseTxid; + round.coinbaseValue = coinbaseValue; + round.foundBy = foundBy; + round.feePercent = dPoolFeePercent; + round.totalShares = total; + round.shares = shareCount; + if (total == 0) { + RecordPoolRound(round); LogPrint("payout", "[payout] block %d: zero shares recorded -- nothing to pay out\n", blockHeight); return; @@ -418,9 +633,13 @@ static void QueuePayouts(int blockHeight, int64 nSubsidy = 50 * COIN; nSubsidy >>= (blockHeight / 210000); // halving schedule int64 minerReward = (int64)((double)nSubsidy * (1.0 - feeFrac)); + int64 operatorCut = nSubsidy - minerReward; + round.subsidy = nSubsidy; + round.minerReward = minerReward; + round.operatorReward = operatorCut; PendingPayout pp; - pp.id = PayoutIdForBlock(blockHeight); + pp.id = round.id; pp.blockHeight = blockHeight; pp.matureAtHeight = blockHeight + COINBASE_MATURITY; @@ -443,15 +662,18 @@ static void QueuePayouts(int blockHeight, continue; } pp.amounts[kv.first] = amount; + round.payouts[kv.first] = amount; } + round.skippedDust = skipped; + round.forfeitedBadAddress = burned; { std::lock_guard lk(gPayoutLedgerMutex); gPendingPayouts.push_back(pp); SavePendingPayoutsLocked(); } + RecordPoolRound(round); - int64 operatorCut = nSubsidy - minerReward; LogPrint("payout", "[payout] block %d: subsidy %s BTF, miners get %s" " (fee %.2f%% = %s to operator)," @@ -548,12 +770,14 @@ static void PayoutThreadFn(void*) LogPrint("payout", "[payout] recovered recorded payout %s to %s" " from wallet tx %s\n", FormatMoney(kv.second).c_str(), kv.first.c_str(), txid.c_str()); + MarkPoolRoundPaid(ppQueued.id, kv.first, txid); } else if (SendMoney(sc, kv.second, wtx)) { txid = wtx.GetHash().GetHex(); LogPrint("payout", "[payout] paid %s to %s\n", FormatMoney(kv.second).c_str(), kv.first.c_str()); + MarkPoolRoundPaid(ppQueued.id, kv.first, txid); } else { @@ -664,7 +888,8 @@ static void WritePoolStatusJsonLocked() {"name", strPoolName}, {"btfAddress", BtfLocalAddress()}, {"feePercent", dPoolFeePercent}, - {"dashboardUrl", strPoolDashboardUrl} + {"dashboardUrl", strPoolDashboardUrl}, + {"roundsFile", "pool_rounds.json"} }; j["node"] = { @@ -702,6 +927,30 @@ static void WritePoolStatusJsonLocked() }); } + j["recentRounds"] = nlohmann::json::array(); + { + std::lock_guard lk(gPoolRoundsMutex); + size_t start = gPoolRounds.size() > 10 ? gPoolRounds.size() - 10 : 0; + for (size_t i = start; i < gPoolRounds.size(); i++) { + const PoolRoundProof& r = gPoolRounds[i]; + int unpaid = 0; + for (const auto& kv : r.payouts) + if (r.paidTxids.count(kv.first) == 0) + unpaid++; + j["recentRounds"].push_back({ + {"id", r.id}, + {"blockHeight", r.blockHeight}, + {"blockHash", r.blockHash}, + {"coinbaseTxid", r.coinbaseTxid}, + {"totalShares", r.totalShares}, + {"payouts", (int)r.payouts.size()}, + {"unpaidPayouts", unpaid}, + {"coinbaseValueBtf", FormatMoney(r.coinbaseValue)}, + {"minerRewardBtf", FormatMoney(r.minerReward)} + }); + } + } + std::string path = PoolStatusFilePath(); std::string tmp = path + ".tmp"; FILE* f = fopen(tmp.c_str(), "w"); @@ -1231,7 +1480,9 @@ static bool HandleLine(Miner* m, const std::string& rawLine, if (accepted) { // Snapshot height before RebuildJob() (which increments it) int foundHeight = gCurrentJob.height; - QueuePayouts(foundHeight, roundShareCount, roundShareTotal); + QueuePayouts(foundHeight, b.GetHash().GetHex(), b.vtx[0].GetHash().GetHex(), + b.vtx[0].vout[0].nValue, m->address, + roundShareCount, roundShareTotal); // Reset round shares roundShareCount.clear(); roundShareTotal = 0; @@ -1333,6 +1584,62 @@ int RunPoolStratumSelfTest() HandleLine(&miner, stale.dump(), roundShareCount, roundShareTotal, blocksFound); check(roundShareTotal == 1, "stale submit does not increment shares"); + std::vector savedRounds = gPoolRounds; + std::string savedRoundsFile = strPoolRoundsFile; + std::string proofPath = "pool_rounds_selftest.json"; + remove(proofPath.c_str()); + remove((proofPath + ".tmp").c_str()); + gPoolRounds.clear(); + strPoolRoundsFile = proofPath; + + PoolRoundProof proof; + proof.id = "selftest-round"; + proof.blockHeight = 42; + proof.matureAtHeight = 42 + COINBASE_MATURITY; + proof.createdAt = GetTime(); + proof.blockHash = block.GetHash().GetHex(); + proof.coinbaseTxid = coinbase.GetHash().GetHex(); + proof.foundBy = miner.address; + proof.feePercent = 1.25; + proof.totalShares = 3; + proof.coinbaseValue = 50 * COIN; + proof.subsidy = 50 * COIN; + proof.minerReward = 49 * COIN; + proof.operatorReward = 1 * COIN; + proof.shares[miner.address] = 3; + proof.payouts[miner.address] = 49 * COIN; + RecordPoolRound(proof); + MarkPoolRoundPaid(proof.id, miner.address, "selftest-txid"); + + bool proofOk = false; + FILE* pf = fopen(proofPath.c_str(), "r"); + if (pf) { + fseek(pf, 0, SEEK_END); + long sz = ftell(pf); + fseek(pf, 0, SEEK_SET); + std::string s(sz, '\0'); + fread(&s[0], 1, sz, pf); + fclose(pf); + try { + json root = json::parse(s); + proofOk = + root.value("schema", "") == "bitflash-pool-rounds-1" && + root["rounds"].is_array() && + root["rounds"].size() == 1 && + root["rounds"][0].value("id", "") == proof.id && + root["rounds"][0]["shares"].value(miner.address, (uint64)0) == 3 && + root["rounds"][0]["payouts"][miner.address].value("txid", "") == "selftest-txid"; + } catch (...) { + proofOk = false; + } + } + check(proofOk, "pool round proof ledger is written and paid txid is recorded"); + + remove(proofPath.c_str()); + remove((proofPath + ".tmp").c_str()); + strPoolRoundsFile = savedRoundsFile; + gPoolRounds = savedRounds; + gCurrentJob = savedJob; gHaveJob = savedHaveJob; @@ -1754,6 +2061,7 @@ void ThreadRPCServer(void*) } LoadPendingPayouts(); + LoadPoolRounds(); _beginthread(AcceptLoopFn, 0, NULL); _beginthread(ThreadBtfPoolAnnouncer, 0, NULL); -- cgit v1.2.3 From dfbf7a91caa4a85da7ce10fa296cfa6d2ead5d0c Mon Sep 17 00:00:00 2001 From: Bitflash Date: Tue, 11 Aug 2026 09:57:29 -0300 Subject: wallet: SLIP-0044 4346950 is official, drop 'provisional' naming The coin type 4346950 (0x425446 = BTF) was merged into the SLIP-0044 registry on 2026-08-07. Rename HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL to HD_BIP44_COIN_TYPE_BITFLASH and update comments, logs and UI strings. Value is unchanged, so derivation paths and addresses are identical. --- src/db.cpp | 6 +++--- src/gui.cpp | 2 +- src/main.cpp | 6 +++--- src/main.h | 8 ++++---- src/selftest.cpp | 12 ++++++------ src/walletcmd.cpp | 2 +- 6 files changed, 18 insertions(+), 18 deletions(-) (limited to 'src/main.cpp') diff --git a/src/db.cpp b/src/db.cpp index 244d5a7..9f62964 100644 --- a/src/db.cpp +++ b/src/db.cpp @@ -880,9 +880,9 @@ bool CWalletDB::LoadWallet(vector& vchDefaultKeyRet) } if (!fHaveStoredHDCoinType) { - nHDCoinType = HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL; + nHDCoinType = HD_BIP44_COIN_TYPE_BITFLASH; printf("LoadWallet: deterministic seed has no BIP44 coin type metadata; " - "using provisional Bitflash coin type %u\n", nHDCoinType); + "using Bitflash coin type %u\n", nHDCoinType); } } else @@ -891,7 +891,7 @@ bool CWalletDB::LoadWallet(vector& vchDefaultKeyRet) nHDNext = 0; nHDReceiveNext = 0; nHDChangeNext = 0; - nHDCoinType = HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL; + nHDCoinType = HD_BIP44_COIN_TYPE_BITFLASH; } // fGenerateBitcoins and nMineMode only mean anything together, and a diff --git a/src/gui.cpp b/src/gui.cpp index 8f1d204..8dcb854 100644 --- a/src/gui.cpp +++ b/src/gui.cpp @@ -1250,7 +1250,7 @@ static void DrawWalletSafetyDialog() if (g_recoveryAudit.fHaveSeed) { ImGui::Text("Derivation schema: %s", HDKeySchemaName(g_recoveryAudit.nSchema).c_str()); - ImGui::Text("BIP44 coin type: %u (provisional BITFLASH)", g_recoveryAudit.nCoinType); + ImGui::Text("BIP44 coin type: %u (SLIP-0044 BITFLASH)", g_recoveryAudit.nCoinType); } ImGui::Text("Phrase-backed spendable balance: %s BTF", FmtMoney(g_recoveryAudit.nRecoverableCredit).c_str()); diff --git a/src/main.cpp b/src/main.cpp index 2eb0e3a..f83164f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -642,7 +642,7 @@ unsigned int nHDNext = 0; int nHDKeySchema = HD_SCHEMA_NONE; unsigned int nHDReceiveNext = 0; unsigned int nHDChangeNext = 0; -unsigned int nHDCoinType = HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL; +unsigned int nHDCoinType = HD_BIP44_COIN_TYPE_BITFLASH; string HDKeySchemaName(int nSchema) { @@ -798,7 +798,7 @@ bool SetHDSeedFromMnemonic(const string& strMnemonic, string& strErrorRet) if (!CWalletDB().WriteHDMaster(master.privateKey, master.chainCode) || !CWalletDB().WriteHDSchema(HD_SCHEMA_BIP44) || - !CWalletDB().WriteHDCoinType(HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL) || + !CWalletDB().WriteHDCoinType(HD_BIP44_COIN_TYPE_BITFLASH) || !CWalletDB().WriteHDNext(0) || !CWalletDB().WriteHDReceiveNext(1) || !CWalletDB().WriteHDChangeNext(0)) @@ -811,7 +811,7 @@ bool SetHDSeedFromMnemonic(const string& strMnemonic, string& strErrorRet) nHDKeySchema = HD_SCHEMA_BIP44; nHDReceiveNext = 1; nHDChangeNext = 0; - nHDCoinType = HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL; + nHDCoinType = HD_BIP44_COIN_TYPE_BITFLASH; // Index 0 is spoken for before it is derived, so a failure below cannot // leave the pool free to hand it out as an ordinary key. The cost of diff --git a/src/main.h b/src/main.h index eafbf16..b389f1d 100644 --- a/src/main.h +++ b/src/main.h @@ -216,9 +216,9 @@ static const unsigned int HD_BIP44_PURPOSE = 44; static const unsigned int HD_BIP44_ACCOUNT = 0; static const unsigned int HD_BIP44_CHAIN_RECEIVE = 0; static const unsigned int HD_BIP44_CHAIN_CHANGE = 1; -// Provisional until Bitflash has an official SLIP-0044 assignment. -// Proposed registry row: 4346950 | BITFLASH | Bitflash. -static const unsigned int HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL = 4346950; +// Official SLIP-0044 assignment (registered 2026-08-07): +// 4346950 | BITFLASH | Bitflash (4346950 == 0x425446 == "BTF") +static const unsigned int HD_BIP44_COIN_TYPE_BITFLASH = 4346950; extern int nHDKeySchema; extern unsigned int nHDReceiveNext; // BIP44 external chain extern unsigned int nHDChangeNext; // BIP44 internal chain @@ -316,7 +316,7 @@ struct WalletRecoveryAudit nDerivedKnown = 0; nReceiveNext = 0; nChangeNext = 0; - nCoinType = HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL; + nCoinType = HD_BIP44_COIN_TYPE_BITFLASH; nRecoverableTx = 0; nLegacyTx = 0; nRecoverableImmatureTx = 0; diff --git a/src/selftest.cpp b/src/selftest.cpp index fadc959..69a3596 100644 --- a/src/selftest.cpp +++ b/src/selftest.cpp @@ -350,17 +350,17 @@ static int RunWalletHDSelfTest() nFail += Check(HaveHDSeed(), "the wallet reports having a seed") ? 0 : 1; nFail += Check(nHDKeySchema == HD_SCHEMA_BIP44, "a new recovery phrase records the BIP44 HD schema") ? 0 : 1; - nFail += Check(nHDCoinType == HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL, - "a new recovery phrase records the provisional BIP44 coin type") ? 0 : 1; + nFail += Check(nHDCoinType == HD_BIP44_COIN_TYPE_BITFLASH, + "a new recovery phrase records the SLIP-0044 BIP44 coin type") ? 0 : 1; nFail += Check(nHDReceiveNext == 1 && nHDChangeNext == 0, "BIP44 receive/change counters reserve the default receive key") ? 0 : 1; - std::vector vBIP44Path = HDBIP44Path(HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL, + std::vector vBIP44Path = HDBIP44Path(HD_BIP44_COIN_TYPE_BITFLASH, HD_BIP44_ACCOUNT, HD_BIP44_CHAIN_RECEIVE, 0); nFail += Check(vBIP44Path.size() == 5 && vBIP44Path[0] == (HD_BIP44_PURPOSE | bitflash::BIP32_HARDENED) && - vBIP44Path[1] == (HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL | bitflash::BIP32_HARDENED) && + vBIP44Path[1] == (HD_BIP44_COIN_TYPE_BITFLASH | bitflash::BIP32_HARDENED) && vBIP44Path[2] == (HD_BIP44_ACCOUNT | bitflash::BIP32_HARDENED) && vBIP44Path[3] == HD_BIP44_CHAIN_RECEIVE && vBIP44Path[4] == 0, @@ -382,7 +382,7 @@ static int RunWalletHDSelfTest() hdParent.chainCode = vchHDChainCode; bitflash::BIP32PrivateNode hdBIP44ReceiveChild; if (!bitflash::BIP32DerivePath(hdParent, - HDBIP44Path(HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL, + HDBIP44Path(HD_BIP44_COIN_TYPE_BITFLASH, HD_BIP44_ACCOUNT, HD_BIP44_CHAIN_RECEIVE, 0), @@ -570,7 +570,7 @@ static int RunWalletHDSelfTest() nFail += Check(audit.fHaveSeed, "the recovery audit reports the phrase") ? 0 : 1; nFail += Check(audit.nSchema == HD_SCHEMA_BIP44, "the recovery audit reports the derivation schema") ? 0 : 1; - nFail += Check(audit.nCoinType == HD_BIP44_COIN_TYPE_BITFLASH_PROVISIONAL, + nFail += Check(audit.nCoinType == HD_BIP44_COIN_TYPE_BITFLASH, "the recovery audit reports the BIP44 coin type") ? 0 : 1; nFail += Check(audit.nReceiveNext == nHDReceiveNext && audit.nChangeNext == 1, "the recovery audit reports receive/change counters") ? 0 : 1; diff --git a/src/walletcmd.cpp b/src/walletcmd.cpp index 06f35a5..0ea2251 100644 --- a/src/walletcmd.cpp +++ b/src/walletcmd.cpp @@ -354,7 +354,7 @@ int CmdRecoveryAudit() if (audit.fHaveSeed) { printf(" derivation schema: %s\n", HDKeySchemaName(audit.nSchema).c_str()); - printf(" BIP44 coin type: %u (provisional BITFLASH)\n", audit.nCoinType); + printf(" BIP44 coin type: %u (SLIP-0044 BITFLASH)\n", audit.nCoinType); printf(" derived keys known to this wallet: %u\n", audit.nDerivedKnown); printf(" receive/change counters: %u/%u\n", audit.nReceiveNext, audit.nChangeNext); -- cgit v1.2.3
StatusPoolFeeMinersH/sBlocksHeightAgeLink
StatusPoolFeeMinersH/sBlocksHeightAgeLinkProof