-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminer_loop.cpp
More file actions
390 lines (323 loc) · 17.5 KB
/
Copy pathminer_loop.cpp
File metadata and controls
390 lines (323 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#include "miner_loop.hpp"
#include "mining_job.hpp"
#include "opencl_utils.hpp"
#include <CL/cl.h>
#include <algorithm>
#include <array>
#include <atomic>
#include <cctype>
#include <chrono>
#include <cstring>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <optional>
#include <random>
#include <string>
#include <thread>
#include <vector>
extern std::atomic<bool> abort_mining;
extern std::atomic<bool> socket_valid;
extern std::atomic<bool> job_wurde_übernommen;
cl_context context = nullptr;
cl_command_queue queue = nullptr;
cl_kernel kernel = nullptr;
cl_program program = nullptr;
cl_device_id device = nullptr;
namespace {
constexpr size_t HASH_SIZE = 32;
constexpr size_t INPUT_BUFFER_SIZE = 512;
inline bool is_hex_char(unsigned char c) {
return std::isxdigit(c) != 0;
}
bool is_valid_hex(const std::string& s, bool allow_0x_prefix = true) {
if (s.empty()) return false;
std::string clean = s;
if (allow_0x_prefix && s.size() >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
clean = s.substr(2);
}
if (clean.empty() || (clean.size() % 2) != 0) return false;
for (unsigned char c : clean) {
if (!is_hex_char(c)) return false;
}
return true;
}
std::string remove_0x_prefix(const std::string& s) {
if (s.size() >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
return s.substr(2);
}
return s;
}
void append_hex_to_buffer(const std::string& hex, std::vector<cl_uchar>& buffer,
const std::string& field_name = "") {
if (hex.empty()) return;
std::string clean_hex = remove_0x_prefix(hex);
if (!is_valid_hex(clean_hex, false)) {
throw std::invalid_argument("Ungültiger Hex-String für Feld '" +
field_name + "': " + hex);
}
buffer.reserve(buffer.size() + clean_hex.size() / 2);
for (size_t i = 0; i < clean_hex.size(); i += 2) {
try {
unsigned long byte_val =
std::stoul(clean_hex.substr(i, 2), nullptr, 16);
if (byte_val > 0xFF) {
throw std::out_of_range("Byte-Wert außerhalb des Bereichs");
}
buffer.push_back(static_cast<cl_uchar>(byte_val));
} catch (const std::exception& e) {
throw std::invalid_argument("Konvertierungsfehler in Feld '" +
field_name + "' bei Position " +
std::to_string(i) + ": " + e.what());
}
}
}
void build_input_from_job(const MiningJob &job, std::vector<cl_uchar> &input_buffer) {
input_buffer.clear();
auto append_hex = [&](const std::string &hex) {
if (hex.empty()) return;
try {
for (size_t i = 0; i + 1 < hex.size(); i += 2) {
std::string byte_str = hex.substr(i, 2);
if (byte_str.find_first_not_of("0123456789abcdefABCDEF") !=
std::string::npos) {
throw std::invalid_argument("Ungültiges Hex-Zeichen");
}
input_buffer.push_back(
static_cast<cl_uchar>(std::stoul(byte_str, nullptr, 16)));
}
} catch (const std::exception &e) {
std::cerr << "❌ Hex-Parsing-Fehler: " << e.what() << "\n";
input_buffer.clear();
}
};
append_hex(job.version);
append_hex(job.prevhash);
append_hex(job.ntime);
append_hex(job.coinb1);
append_hex(job.extranonce1);
append_hex(job.extranonce2);
append_hex(job.coinb2);
for (const auto &hash : job.merkle_branch)
append_hex(hash);
}
void init_opencl() {
if (context) return;
cl_int err = CL_SUCCESS;
cl_platform_id platform = nullptr;
clGetPlatformIDs(1, &platform, nullptr);
clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, nullptr);
cl_uint num_platforms = 0;
clGetPlatformIDs(0, nullptr, &num_platforms);
std::vector<cl_platform_id> platforms(num_platforms);
clGetPlatformIDs(num_platforms, platforms.data(), nullptr);
for (auto p : platforms) {
cl_uint num_devices = 0;
clGetDeviceIDs(p, CL_DEVICE_TYPE_GPU, 0, nullptr, &num_devices);
std::vector<cl_device_id> devices(num_devices);
clGetDeviceIDs(p, CL_DEVICE_TYPE_GPU, num_devices, devices.data(), nullptr);
for (auto d : devices) {
char vendor[256] = {0};
clGetDeviceInfo(d, CL_DEVICE_VENDOR, sizeof(vendor), vendor, nullptr);
if (strstr(vendor, "Intel(R) Corporation")) {
device = d;
platform = p;
break;
}
}
if (device) break;
}
context = clCreateContext(nullptr, 1, &device, nullptr, nullptr, &err);
queue = clCreateCommandQueueWithProperties(context, device, 0, &err);
std::ifstream file("kernels/zhash.cl");
if (!file) {
std::cerr << "❌ Konnte Kernel-Datei nicht öffnen.\n";
std::exit(1);
}
std::string source((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
const char *src = source.c_str();
size_t size = source.size();
program = clCreateProgramWithSource(context, 1, &src, &size, &err);
err = clBuildProgram(program, 1, &device, nullptr, nullptr, nullptr);
char build_log[65536] = {0};
size_t log_size = 0;
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,
sizeof(build_log), build_log, &log_size);
std::cerr << "--- CL BUILD LOG (" << log_size << " bytes) ---\n"
<< build_log << "\n-----------------\n";
if (err != CL_SUCCESS) {
size_t log_size2 = 0;
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0, nullptr,
&log_size2);
std::vector<char> log(log_size2);
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, log_size2,
log.data(), nullptr);
std::cerr << "❌ Build-Fehler:\n" << log.data() << "\n";
std::exit(1);
}
kernel = clCreateKernel(program, "zhash_144_5", &err);
if (kernel == nullptr) {
std::cerr << "ERROR: Kernel creation failed\n";
}
}
bool is_valid_candidate_pair(const std::vector<uint8_t> &hashA,
const std::vector<uint8_t> &hashB) {
if (hashA.empty() || hashB.empty()) return false;
return (hashA[0] ^ hashB[0]) == 0;
}
std::string sanitize_hex_string(const std::string &input) {
std::string output;
output.reserve(input.size());
for (char c : input) {
if (std::isxdigit(static_cast<unsigned char>(c))) {
output.push_back(c);
}
}
return output;
}
std::optional<uint32_t> safe_stoul_hex(const std::string& hex_str) {
try {
size_t idx = 0;
uint32_t value = std::stoul(hex_str, &idx, 16);
if (idx != hex_str.size()) return std::nullopt;
return value;
} catch (...) {
return std::nullopt;
}
}
} // namespace
void miner_loop(
GpuResources& resources,
const std::function<MiningJob()> get_current_job,
const std::function<void(uint32_t, const std::array<uint8_t, 32>&, const MiningJob&)>& on_valid_share,
int intensity
) {
std::cout << "🏗️ Miner-Loop gestartet mit Intensität " << intensity << "\n";
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_int_distribution<uint32_t> dist;
MiningJob current_job = get_current_job();
std::string current_job_id = current_job.job_id;
const size_t local_work_size = 256;
const size_t min_intensity = 1;
const size_t batch_size = static_cast<size_t>(std::max<int>(min_intensity, intensity)) * 4096ULL;
auto clean_bits = sanitize_hex_string(current_job.nbits);
auto maybe_bits = safe_stoul_hex(clean_bits);
if (!maybe_bits) return;
std::vector<uint8_t> target = bits_to_target(*maybe_bits);
std::vector<cl_uchar> host_input_buffer;
try {
build_input_from_job(current_job, host_input_buffer);
} catch (const std::exception& e) {
std::cerr << "❌ Fehler beim Erstellen des Eingabepuffers (initial): " << e.what() << "\n";
return;
}
host_input_buffer.resize(512, 0);
const size_t global_work_size = ((batch_size + local_work_size - 1) / local_work_size) * local_work_size;
std::vector<cl_uchar> output_buffer(32 * batch_size);
std::vector<cl_uint> index_buffer(2 * batch_size, 0);
cl_int err = CL_SUCCESS;
// Annahme: CLMemWrapper hat einen Konstruktor, der ein cl_mem aufnimmt und ein Member 'mem' bereitstellt.
CLMemWrapper cl_input(clCreateBuffer(resources.context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, 512, host_input_buffer.data(), &err));
if (!check_cl(err, "clCreateBuffer(cl_input)", &resources)) return;
CLMemWrapper cl_output(clCreateBuffer(resources.context, CL_MEM_WRITE_ONLY, output_buffer.size(), nullptr, &err));
if (!check_cl(err, "clCreateBuffer(cl_output)", &resources)) return;
CLMemWrapper cl_indexes(clCreateBuffer(resources.context, CL_MEM_WRITE_ONLY, index_buffer.size() * sizeof(cl_uint), nullptr, &err));
if (!check_cl(err, "clCreateBuffer(cl_indexes)", &resources)) return;
CLMemWrapper cl_solution_count(clCreateBuffer(resources.context, CL_MEM_READ_WRITE, sizeof(cl_uint), nullptr, &err));
if (!check_cl(err, "clCreateBuffer(cl_solution_count)", &resources)) return;
while (!abort_mining && socket_valid) {
// Neues Job-Handling
MiningJob new_job = get_current_job();
if (new_job.job_id != current_job_id) {
std::cout << "🔄 Neuer Job empfangen: " << new_job.job_id << "\n";
current_job = new_job;
current_job_id = new_job.job_id;
// rebuild input + target on job change
try {
build_input_from_job(current_job, host_input_buffer);
host_input_buffer.resize(512, 0);
} catch (const std::exception& e) {
std::cerr << "❌ Fehler beim Erstellen des Eingabepuffers: " << e.what() << "\n";
continue;
}
auto clean_bits2 = sanitize_hex_string(current_job.nbits);
auto maybe_bits2 = safe_stoul_hex(clean_bits2);
if (!maybe_bits2) {
std::cerr << "❌ Ungültige nbits: " << current_job.nbits << "\n";
continue;
}
target = bits_to_target(*maybe_bits2);
}
const uint32_t start_nonce = dist(rng);
const cl_uint zero = 0;
if (!check_cl(clEnqueueWriteBuffer(resources.queue, cl_solution_count.mem, CL_TRUE, 0, sizeof(cl_uint), &zero, 0, nullptr, nullptr),
"clEnqueueWriteBuffer(solution_count=0)", &resources)) {
continue;
}
if (!check_cl(clEnqueueWriteBuffer(resources.queue, cl_input.mem, CL_TRUE, 0, host_input_buffer.size(), host_input_buffer.data(), 0, nullptr, nullptr),
"clEnqueueWriteBuffer(input_data)", &resources)) {
continue;
}
if (!check_cl(clSetKernelArg(resources.kernel, 0, sizeof(cl_mem), &cl_input.mem), "clSetKernelArg(0, cl_input)", &resources)) continue;
if (!check_cl(clSetKernelArg(resources.kernel, 1, sizeof(cl_mem), &cl_output.mem), "clSetKernelArg(1, cl_output)", &resources)) continue;
if (!check_cl(clSetKernelArg(resources.kernel, 2, sizeof(cl_mem), &cl_indexes.mem), "clSetKernelArg(2, cl_indexes)", &resources)) continue;
if (!check_cl(clSetKernelArg(resources.kernel, 3, sizeof(cl_mem), &cl_solution_count.mem), "clSetKernelArg(3, cl_solution_count)", &resources)) continue;
if (!check_cl(clSetKernelArg(resources.kernel, 4, sizeof(uint32_t), &start_nonce), "clSetKernelArg(4, start_nonce)", &resources)) continue;
std::cout << "Starting mining loop with:\n";
std::cout << " Job ID: " << current_job.job_id << "\n";
std::cout << " PrevHash: " << current_job.prevhash << "\n";
std::cout << " Target: " << current_job.nbits << "\n";
std::cout << " Intensity: " << intensity << "\n";
cl_event evt = nullptr;
err = clEnqueueNDRangeKernel(resources.queue, resources.kernel, 1, nullptr,
&global_work_size, &local_work_size, 0,
nullptr, &evt);
if (!check_cl(err, "clEnqueueNDRangeKernel", &resources)) {
if (evt) clReleaseEvent(evt);
continue;
}
clWaitForEvents(1, &evt);
clReleaseEvent(evt);
if (!check_cl(clEnqueueReadBuffer(resources.queue, cl_output.mem, CL_TRUE, 0, output_buffer.size(), output_buffer.data(), 0, nullptr, nullptr),
"clEnqueueReadBuffer(output)", &resources)) continue;
if (!check_cl(clEnqueueReadBuffer(resources.queue, cl_indexes.mem, CL_TRUE, 0, index_buffer.size() * sizeof(cl_uint), index_buffer.data(), 0, nullptr, nullptr),
"clEnqueueReadBuffer(indexes)", &resources)) continue;
cl_uint solution_count = 0;
if (!check_cl(clEnqueueReadBuffer(resources.queue, cl_solution_count.mem, CL_TRUE, 0, sizeof(cl_uint), &solution_count, 0, nullptr, nullptr),
"clEnqueueReadBuffer(solution_count)", &resources)) continue;
for (size_t i = 0; i < batch_size; ++i) {
const uint32_t idxA = index_buffer[i * 2];
const uint32_t idxB = index_buffer[i * 2 + 1];
if (idxA == 0 && idxB == 0) continue;
if (idxA >= batch_size || idxB >= batch_size) continue;
std::array<uint8_t, 32> final_hash;
for (int j = 0; j < 32; ++j) {
final_hash[j] = output_buffer[idxA * 32 + j] ^ output_buffer[idxB * 32 + j];
}
if (is_valid_hash(final_hash, target)) {
const uint32_t found_nonce = start_nonce + idxA;
std::cout << "✅ Gültiger Share gefunden! Nonce: " << found_nonce << "\n";
// Callback für lokale Verarbeitung (z.B. Logging oder DB)
on_valid_share(found_nonce, final_hash, current_job);
// Schritt 8: Share an Pool senden
try {
// Beispielstruktur für JSON-Stratum-Submit (Platzhalter)
std::ostringstream json;
json << R"({"method": "mining.submit", "params": [")"
<< current_job.worker_name << R"(", ")"
<< current_job.job_id << R"(", ")"
<< to_hex(final_hash) << R"("], "id": 1})";
// Annahme: es gibt send_to_pool(const std::string& json)
send_to_pool(json.str());
std::cout << "📤 Share erfolgreich an Pool gesendet.\n";
} catch (const std::exception& e) {
std::cerr << "❌ Fehler beim Senden des Shares an Pool: " << e.what() << "\n";
}
}
}
}
}