stratum: RandomX pool mining support + reference miner (stratummine)

The stratum server was hardcoded for legacy Equihash (1347-byte solution,
sol.begin()+3 offset, CheckEquihashSolution) and was off-by-default with a
"do not use on RandomX" warning. DragonX is RandomX, so external pool mining
was impossible. This wires RandomX end-to-end.

Server (stratum.cpp), branched on ASSETCHAINS_ALGO == ASSETCHAINS_RANDOMX:
* GetWorkUnit sets StratumWork.nHeight and, for RandomX, sends the per-height
  RandomX key via a new mining.set_randomx_key message (a miner cannot derive
  it without the chain). The legacy mining.notify format is unchanged.
* SubmitBlock/stratum_mining_submit accept a 32-byte solution (== the RandomX
  hash, used as nSolution verbatim) and validate it with CheckRandomXSolution
  instead of CheckEquihashSolution. Target check (GetHash() < target) and the
  nNonce = extranonce1||extranonce2 assembly are shared with the equihash path.
* -stratumtarget=<hex> overrides the pool share target (default diff-1); lets a
  solo/low-difficulty test miner accept easy shares.
* GetWorkUnit's IsInitialBlockDownload guard is bypassed under -testnode=1 so an
  isolated low-work test chain can serve work.

Reference miner: `stratummine "host" port ("address" timeout)` RPC (rpc/mining.cpp,
POSIX-only). A minimal stratum client that subscribes/authorizes, receives work +
the RandomX key, varies nNonce, hashes with RandomX via GetRandomXInput (byte-
identical to CheckRandomXSolution) and submits a 32-byte solution. Off-the-shelf
Equihash/Monero miners can't speak DragonX's 256-bit-nNonce Zcash header, so this
is the reference implementation. Added to the rpc client arg-conversion table.

Validated: loopback (chain 0->4, accepted every time, verifychain=true) AND a real
2-box LAN run (Linux miner -> Mac stratum server, 3 blocks accepted, verifychain=true).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-08-27 20:24:13 -05:00
parent 1745ee4e63
commit 2232868d9f
4 changed files with 330 additions and 33 deletions

View File

@@ -45,6 +45,21 @@
#include <univalue.h>
#include "compat/byteswap.h" // bswap_32 for the stratum wire fields (version/time/bits)
#ifndef WIN32
// stratummine (below) is a POSIX-only reference RandomX stratum miner used to exercise the pool
// path end-to-end. It reuses DragonX's own RandomX + GetRandomXInput so its hash is byte-identical
// to CheckRandomXSolution. Not built on Windows (raw POSIX sockets).
#include "RandomX/src/randomx.h"
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#endif
using namespace std;
#include "hush_defs.h"
@@ -1053,9 +1068,242 @@ UniValue getblocksubsidy(const UniValue& params, bool fHelp, const CPubKey& mypk
}
#ifndef WIN32
extern uint32_t ASSETCHAINS_ALGO, ASSETCHAINS_RANDOMX; // hush_defs.h — active PoW algorithm
// Send one newline-terminated JSON line on a blocking socket.
static bool StratumMinerSend(int fd, const std::string& s)
{
std::string line = s;
if (line.empty() || line.back() != '\n') line += '\n';
size_t off = 0;
while (off < line.size()) {
ssize_t n = send(fd, line.data() + off, line.size() - off, 0);
if (n <= 0) return false;
off += (size_t)n;
}
return true;
}
// Wait up to timeout_ms for data, then split all completed lines out of buf into out.
// Returns false only on socket error/close (a timeout with no data is success with out empty).
static bool StratumMinerRecvLines(int fd, std::string& buf, int timeout_ms, std::vector<std::string>& out)
{
fd_set rfds; FD_ZERO(&rfds); FD_SET(fd, &rfds);
struct timeval tv; tv.tv_sec = timeout_ms / 1000; tv.tv_usec = (timeout_ms % 1000) * 1000;
int r = select(fd + 1, &rfds, NULL, NULL, &tv);
if (r < 0) return false;
if (r == 0) return true;
char tmp[8192];
ssize_t n = recv(fd, tmp, sizeof(tmp), 0);
if (n <= 0) return false;
buf.append(tmp, tmp + n);
size_t pos;
while ((pos = buf.find('\n')) != std::string::npos) {
std::string line = buf.substr(0, pos);
buf.erase(0, pos + 1);
if (!line.empty() && line.back() == '\r') line.pop_back();
if (!line.empty()) out.push_back(line);
}
return true;
}
// Reference RandomX stratum miner (test utility): connect to a DragonX stratum server, subscribe +
// authorize, receive work + the per-height RandomX key, then vary the block nNonce, hash with
// RandomX (byte-identical to CheckRandomXSolution via GetRandomXInput), and submit a 32-byte
// solution when the block hash meets target. Exists to validate the -stratum RandomX pool path.
UniValue stratummine(const UniValue& params, bool fHelp, const CPubKey& mypk)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"stratummine \"host\" port ( \"address\" timeout )\n"
"\nReference RandomX stratum miner: connect to a DragonX stratum server, solve RandomX,\n"
"and submit until one share/block is accepted or the timeout elapses. For testing -stratum.\n"
"\nArguments:\n"
"1. \"host\" (string, required) stratum server host or IP\n"
"2. port (numeric, required) stratum server port\n"
"3. \"address\" (string, optional, default=\"x\") payout R-address, or \"x\" for the server default\n"
"4. timeout (numeric, optional, default=120) seconds to mine before giving up\n"
"\nResult: {\"found\":bool,\"accepted\":bool,\"hash\":\"..\",\"hashes\":n,\"seconds\":n}\n");
if (ASSETCHAINS_ALGO != ASSETCHAINS_RANDOMX)
throw JSONRPCError(RPC_MISC_ERROR, "stratummine only supports RandomX chains");
const std::string host = params[0].get_str();
const int port = params[1].get_int();
const std::string addr = params.size() > 2 ? params[2].get_str() : "x";
const int64_t timeout = params.size() > 3 ? params[3].get_int64() : 120;
const int64_t deadline = GetTime() + timeout;
// connect (blocking TCP)
struct addrinfo hints; memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM;
struct addrinfo* ai = NULL;
if (getaddrinfo(host.c_str(), strprintf("%d", port).c_str(), &hints, &ai) != 0 || !ai)
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, strprintf("cannot resolve %s:%d", host, port));
int fd = -1;
for (struct addrinfo* p = ai; p; p = p->ai_next) {
fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (fd < 0) continue;
if (connect(fd, p->ai_addr, p->ai_addrlen) == 0) break;
close(fd); fd = -1;
}
freeaddrinfo(ai);
if (fd < 0)
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, strprintf("cannot connect to %s:%d", host, port));
{ int one = 1; setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*)&one, sizeof(one)); }
StratumMinerSend(fd, "{\"id\":1,\"method\":\"mining.subscribe\",\"params\":[\"dragonx-refminer/1.0\"]}");
StratumMinerSend(fd, strprintf("{\"id\":2,\"method\":\"mining.authorize\",\"params\":[\"%s\",\"x\"]}", addr));
// state accumulated from the server
std::vector<unsigned char> extranonce1;
std::string rxKey;
bool haveKey = false, haveTarget = false, haveJob = false;
arith_uint256 poolTarget;
std::string jobId, timeHex;
uint32_t nVersion = 4, nTime = 0, nBits = 0;
uint256 hashPrevBlock, hashMerkleRoot, hashReserved;
auto processLine = [&](const std::string& line) {
UniValue v;
if (!v.read(line)) return;
const UniValue& id = find_value(v, "id");
const UniValue& result = find_value(v, "result");
if (id.isNum() && id.get_int() == 1 && result.isArray() && result.size() >= 2 && result[1].isStr())
extranonce1 = ParseHex(result[1].get_str());
const UniValue& method = find_value(v, "method");
if (!method.isStr()) return;
const UniValue& p = find_value(v, "params");
if (!p.isArray()) return;
const std::string m = method.get_str();
if (m == "mining.set_randomx_key" && p.size() >= 1) {
std::vector<unsigned char> kb = ParseHex(p[0].get_str());
rxKey.assign(kb.begin(), kb.end());
haveKey = true;
} else if (m == "mining.set_target" && p.size() >= 1) {
poolTarget = UintToArith256(uint256S(p[0].get_str()));
haveTarget = true;
} else if (m == "mining.notify" && p.size() >= 7) {
jobId = p[0].get_str();
nVersion = bswap_32((uint32_t)strtoul(p[1].get_str().c_str(), NULL, 16));
hashPrevBlock = uint256(ParseHex(p[2].get_str()));
hashMerkleRoot = uint256(ParseHex(p[3].get_str()));
hashReserved = uint256(ParseHex(p[4].get_str()));
timeHex = p[5].get_str();
nTime = bswap_32((uint32_t)strtoul(timeHex.c_str(), NULL, 16));
nBits = bswap_32((uint32_t)strtoul(p[6].get_str().c_str(), NULL, 16));
haveJob = true;
}
};
std::string buf;
for (int i = 0; i < 120 && !(haveJob && haveTarget && haveKey && !extranonce1.empty()); i++) {
std::vector<std::string> lines;
if (!StratumMinerRecvLines(fd, buf, 250, lines)) { close(fd); throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "stratum connection closed during handshake"); }
for (const std::string& l : lines) processLine(l);
if (GetTime() > deadline) break;
}
if (!(haveJob && haveTarget && haveKey && !extranonce1.empty())) {
close(fd);
throw JSONRPCError(RPC_MISC_ERROR, "did not receive complete RandomX work (need job + target + randomx key + extranonce)");
}
randomx_flags flags = randomx_get_flags();
randomx_cache* cache = randomx_alloc_cache(flags);
if (!cache) { close(fd); throw JSONRPCError(RPC_MISC_ERROR, "randomx_alloc_cache failed"); }
randomx_init_cache(cache, rxKey.data(), rxKey.size());
std::string vmKey = rxKey;
randomx_vm* vm = randomx_create_vm(flags, cache, NULL);
if (!vm) { randomx_release_cache(cache); close(fd); throw JSONRPCError(RPC_MISC_ERROR, "randomx_create_vm failed"); }
UniValue res(UniValue::VOBJ);
bool found = false, accepted = false, submitted = false;
uint64_t hashes = 0, en2ctr = 0;
std::string foundHash;
const int64_t started = GetTime();
while (GetTime() <= deadline && !found) {
std::string prevJob = jobId;
std::vector<std::string> lines;
if (!StratumMinerRecvLines(fd, buf, 0, lines)) break;
for (const std::string& l : lines) processLine(l);
if (jobId != prevJob) en2ctr = 0; // new tip -> restart the nonce search
if (rxKey != vmKey) { randomx_init_cache(cache, rxKey.data(), rxKey.size()); randomx_vm_set_cache(vm, cache); vmKey = rxKey; }
arith_uint256 blockTarget; bool fNeg, fOver;
blockTarget.SetCompact(nBits, &fNeg, &fOver);
// Mine to the harder of (block target, pool share target) so a solution is a real block AND
// passes the server's low-diff share check.
arith_uint256 tgt = (haveTarget && poolTarget < blockTarget) ? poolTarget : blockTarget;
CBlockHeader hdr;
hdr.nVersion = nVersion;
hdr.hashPrevBlock = hashPrevBlock;
hdr.hashMerkleRoot = hashMerkleRoot;
hdr.hashFinalSaplingRoot = hashReserved;
hdr.nTime = nTime;
hdr.nBits = nBits;
for (int i = 0; i < 2000 && GetTime() <= deadline; i++) {
std::vector<unsigned char> nonce = extranonce1;
nonce.resize(32, 0);
for (int b = 0; b < 8; b++) nonce[8 + b] = (unsigned char)((en2ctr >> (8 * b)) & 0xff);
en2ctr++; hashes++;
hdr.nNonce = uint256(nonce);
std::vector<unsigned char> input = GetRandomXInput(hdr);
unsigned char h[RANDOMX_HASH_SIZE];
randomx_calculate_hash(vm, input.data(), input.size(), h);
hdr.nSolution.assign(h, h + RANDOMX_HASH_SIZE);
if (UintToArith256(hdr.GetHash()) <= tgt) {
std::vector<unsigned char> en2(nonce.begin() + 8, nonce.end());
std::string submit = strprintf(
"{\"id\":4,\"method\":\"mining.submit\",\"params\":[\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"]}",
addr, jobId, timeHex, HexStr(en2), HexStr(hdr.nSolution));
StratumMinerSend(fd, submit);
submitted = true;
foundHash = hdr.GetHash().ToString();
bool sawResult = false;
for (int k = 0; k < 40 && !sawResult; k++) {
std::vector<std::string> rl;
if (!StratumMinerRecvLines(fd, buf, 250, rl)) break;
for (const std::string& l : rl) {
processLine(l);
UniValue rv; if (!rv.read(l)) continue;
const UniValue& rid = find_value(rv, "id");
if (rid.isNum() && rid.get_int() == 4) {
sawResult = true;
const UniValue& r = find_value(rv, "result");
accepted = r.isBool() ? r.get_bool() : find_value(rv, "error").isNull();
}
}
}
found = true;
break;
}
}
}
randomx_destroy_vm(vm);
randomx_release_cache(cache);
close(fd);
res.push_back(Pair("found", found));
res.push_back(Pair("submitted", submitted));
res.push_back(Pair("accepted", accepted));
res.push_back(Pair("hashes", (uint64_t)hashes));
res.push_back(Pair("seconds", (int64_t)(GetTime() - started)));
if (!foundHash.empty()) res.push_back(Pair("hash", foundHash));
return res;
}
#endif // !WIN32
static const CRPCCommand commands[] =
{ // category name actor (function) okSafeMode
// --------------------- ------------------------ ----------------------- ----------
#ifndef WIN32
{ "mining", "stratummine", &stratummine, true },
#endif
{ "mining", "getlocalsolps", &getlocalsolps, true },
{ "mining", "getnetworksolps", &getnetworksolps, true },
{ "mining", "getnetworkhashps", &getnetworkhashps, true },