-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathstratum_task.cpp
More file actions
444 lines (360 loc) · 13.8 KB
/
Copy pathstratum_task.cpp
File metadata and controls
444 lines (360 loc) · 13.8 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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#include "esp_log.h"
#include "esp_sntp.h"
#include "esp_task_wdt.h"
#include "esp_timer.h"
#include "esp_wifi.h"
#include "global_state.h"
#include "lwip/dns.h"
#include "asic_jobs.h"
#include "boards/board.h"
#include "connect.h"
#include "create_jobs_task.h"
#include "global_state.h"
#include "macros.h"
#include "nvs_config.h"
#include "psram_allocator.h"
#include "stratum_task.h"
#include "system.h"
#include "guards.h"
#define ESP_LOGIE(b, tag, fmt, ...) \
do { \
if (b) { \
ESP_LOGI(tag, fmt, ##__VA_ARGS__); \
} else { \
ESP_LOGE(tag, fmt, ##__VA_ARGS__); \
} \
} while (0)
// fallback can nicely be tested with netcat
// socat TCP-LISTEN:5555,fork TCP:solo.ckpool.org:3333
// ============================================================================
// StratumTaskBase
// ============================================================================
StratumTaskBase::StratumTaskBase(StratumManager *manager, int index)
: m_manager(manager), m_index(index)
{
if (!index) {
m_tag = "stratum task (Pri)";
} else {
m_tag = "stratum task (Sec)";
}
m_config = new StratumConfig(index);
}
bool StratumTaskBase::isWifiConnected()
{
wifi_ap_record_t ap_info;
return esp_wifi_sta_get_ap_info(&ap_info) == ESP_OK;
}
bool StratumTaskBase::resolveHostname(const char *hostname, char *ip_str, size_t ip_str_len)
{
struct addrinfo hints;
struct addrinfo *res;
int err;
// Set up the hints for the lookup
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET; // IPv4
// Perform the blocking DNS lookup
err = getaddrinfo(hostname, NULL, &hints, &res);
if (err != 0 || res == NULL) {
ESP_LOGE("DNS", "DNS lookup failed: %d", err);
return false;
}
// Extract the IP address from the result
struct sockaddr_in *addr = (struct sockaddr_in *) res->ai_addr;
inet_ntop(AF_INET, &(addr->sin_addr), ip_str, ip_str_len);
// save IP adrdress
strncpy(m_lastResolvedIp, ip_str, sizeof(m_lastResolvedIp));
m_lastResolvedIp[sizeof(m_lastResolvedIp) - 1] = '\0';
ESP_LOGI("DNS", "Resolved IP: %s", ip_str);
// Free the result
freeaddrinfo(res);
return true;
}
int StratumTaskBase::connectStratum(const char *host_ip, uint16_t port)
{
struct sockaddr_in dest_addr;
dest_addr.sin_addr.s_addr = inet_addr(host_ip);
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(port);
int addr_family = AF_INET;
int ip_protocol = IPPROTO_IP;
int sock = socket(addr_family, SOCK_STREAM, ip_protocol);
if (sock < 0) {
return 0;
}
ESP_LOGI(m_tag, "Socket created, connecting to %s:%d", host_ip, port);
int err = ::connect(sock, (struct sockaddr *) &dest_addr, sizeof(dest_addr));
if (err != 0) {
ESP_LOGE(m_tag, "Connect failed to %s:%d (errno %d: %s)", host_ip, port, errno, strerror(errno));
shutdown(sock, SHUT_RDWR);
close(sock);
return 0;
}
ESP_LOGI(m_tag, "Connected to %s:%d", host_ip, port);
if (!setupSocketTimeouts(sock)) {
ESP_LOGE(m_tag, "Error setting socket timeouts");
}
return sock;
}
bool StratumTaskBase::setupSocketTimeouts(int sock)
{
// we add timeout to prevent recv to hang forever
// if it times out on the recv we will check the connection state
// and retry if still connected
struct timeval timeout;
timeout.tv_sec = 30; // 30 seconds timeout
timeout.tv_usec = 0; // 0 microseconds
ESP_LOGI(m_tag, "Set socket timeout to %d for recv and write", (int) timeout.tv_sec);
if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) {
ESP_LOGE(m_tag, "Failed to set socket receive timeout");
return false;
}
if (setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) < 0) {
ESP_LOGE(m_tag, "Failed to set socket send timeout");
return false;
}
// Enable TCP Keepalive
int enable = Config::isStratumKeepaliveEnabled() ? 1 : 0;
if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &enable, sizeof(enable)) < 0) {
ESP_LOGE(m_tag, "Failed to enable SO_KEEPALIVE");
return false;
}
if (enable) {
// Configure Keepalive parameters
int keepidle = 10; // Start sending keepalive probes after 10 seconds of inactivity
int keepintvl = 5; // Interval of 5 seconds between individual keepalive probes
int keepcnt = 3; // Disconnect after 3 unanswered probes
if (setsockopt(sock, IPPROTO_TCP, TCP_KEEPIDLE, &keepidle, sizeof(keepidle)) < 0) {
ESP_LOGW(m_tag, "TCP_KEEPIDLE not supported or failed to set");
// This might not be critical, so we could just log a warning and continue
}
if (setsockopt(sock, IPPROTO_TCP, TCP_KEEPINTVL, &keepintvl, sizeof(keepintvl)) < 0) {
ESP_LOGE(m_tag, "Failed to set TCP_KEEPINTVL");
}
if (setsockopt(sock, IPPROTO_TCP, TCP_KEEPCNT, &keepcnt, sizeof(keepcnt)) < 0) {
ESP_LOGE(m_tag, "Failed to set TCP_KEEPCNT");
}
ESP_LOGI(m_tag, "TCP Keepalive enabled: idle=%ds, interval=%ds, count=%d", keepidle, keepintvl, keepcnt);
} else {
ESP_LOGI(m_tag, "TCP Keepalive is disabled via config.");
}
return true;
}
void StratumTaskBase::connect()
{
m_stopFlag = false;
}
void StratumTaskBase::disconnect()
{
m_stopFlag = true;
}
void StratumTaskBase::triggerReconnect() {
m_reconnect = true;
}
void StratumTaskBase::reconnectTimerCallbackWrapper(TimerHandle_t xTimer)
{
StratumTaskBase *self = static_cast<StratumTaskBase *>(pvTimerGetTimerID(xTimer));
self->reconnectTimerCallback(xTimer);
}
// Reconnect Timer Callback
void StratumTaskBase::reconnectTimerCallback(TimerHandle_t xTimer)
{
m_manager->reconnectTimerCallback(m_index);
}
// Connected Callback
void StratumTaskBase::connectedCallback()
{
m_manager->connectedCallback(m_index);
}
// Disconnected Callback
void StratumTaskBase::disconnectedCallback()
{
m_manager->disconnectedCallback(m_index);
}
// Start the reconnect timer
void StratumTaskBase::startReconnectTimer()
{
if (m_reconnectTimer == NULL) {
m_reconnectTimer = xTimerCreate("Reconnect Timer", pdMS_TO_TICKS(30000), pdTRUE, this, reconnectTimerCallbackWrapper);
}
// only start the timer when it is not running
if (xTimerIsTimerActive(m_reconnectTimer) == pdFALSE) {
xTimerStart(m_reconnectTimer, 0);
}
}
// Stop the reconnect timer
void StratumTaskBase::stopReconnectTimer()
{
if (m_reconnectTimer != NULL) {
xTimerStop(m_reconnectTimer, 0);
}
}
void StratumTaskBase::taskWrapper(void *pvParameters)
{
StratumTaskBase *task = (StratumTaskBase *) pvParameters;
task->task();
}
void StratumTaskBase::task()
{
// Start the reconnect timer
startReconnectTimer();
while (1) {
if (POWER_MANAGEMENT_MODULE.isShutdown()) {
ESP_LOGW(m_tag, "suspended");
vTaskSuspend(NULL);
}
// gets a guaranteed consistent copy of the config
m_manager->copyConfigInto(m_index, m_config);
m_reconnect = false;
// do we have a stratum host configured?
// we do it here because we could reload the config after
// it was updated on the UI and settings
if (!strlen(m_config->getHost())) {
vTaskDelay(pdMS_TO_TICKS(10000));
continue;
}
// should stay stopped?
if (m_stopFlag) {
vTaskDelay(pdMS_TO_TICKS(10000));
continue;
}
// check if wifi is connected
// esp_wifi_connect is thread safe
if (!isWifiConnected()) {
ESP_LOGI(m_tag, "WiFi disconnected, attempting to reconnect...");
esp_wifi_connect();
vTaskDelay(pdMS_TO_TICKS(10000));
continue;
}
// resolve the IP of the host
char ip[INET_ADDRSTRLEN] = {0};
if (!resolveHostname(m_config->getHost(), ip, sizeof(ip))) {
ESP_LOGE(m_tag, "%s couldn't be resolved!", m_config->getHost());
vTaskDelay(pdMS_TO_TICKS(10000));
continue;
}
ESP_LOGI(m_tag, "Connecting to: stratum+tcp://%s:%d (%s)", m_config->getHost(), m_config->getPort(), ip);
// select transport (protocol-specific)
m_transport = selectTransport();
if (!m_transport->connect(m_config->getHost(), ip, m_config->getPort())) {
ESP_LOGE(m_tag, "Socket unable to connect to %s:%d (errno %d)", m_config->getHost(), m_config->getPort(), errno);
vTaskDelay(pdMS_TO_TICKS(10000));
continue;
}
// we are connected but it doesn't mean the server is alive ...
// protocol-specific loop
protocolLoop();
// track pool errors
// reconnect request is not an error
if (!m_reconnect) {
m_poolErrors++;
}
// gate new submits before tearing the transport down; the
// transport's internal lock covers a submit already inside send()
m_isConnected = false;
// shutdown and reconnect
ESP_LOGIE(m_reconnect, m_tag, "Shutdown socket ...");
m_transport->close();
disconnectedCallback();
// skip reconnect delay
if (m_reconnect) {
continue;
}
vTaskDelay(pdMS_TO_TICKS(10000)); // Delay before attempting to reconnect
}
vTaskDelete(NULL);
}
// ============================================================================
// StratumTaskV1
// ============================================================================
StratumTaskV1::StratumTaskV1(StratumManager *manager, int index)
: StratumTaskBase(manager, index)
{
}
StratumTransport* StratumTaskV1::selectTransport()
{
if (m_config->isTLS()) {
return &m_tlsTransport;
}
return &m_tcpTransport;
}
void StratumTaskV1::protocolLoop()
{
Board *board = SYSTEM_MODULE.getBoard();
m_stratumAPI.resetUid();
m_stratumAPI.clearBuffer();
///// Start Stratum Action
// mining.subscribe - ID: 1
bool success = m_stratumAPI.subscribe(m_transport, board->getMiningAgent(), board->getAsicModel());
// mining.configure - ID: 2
success = success && m_stratumAPI.configureVersionRolling(m_transport);
// mining.authorize - ID: 3
success = success && m_stratumAPI.authenticate(m_transport, m_config->getUser(), m_config->getPassword());
// mining.suggest_difficulty - ID: 4
success = success && m_stratumAPI.suggestDifficulty(m_transport, Config::getStratumDifficulty());
// mining.mining.extranonce.subscribe - ID 5
if (m_config->isEnonceSubscribeEnabled()) {
success = success && m_stratumAPI.entranonceSubscribe(m_transport);
}
if (!success) {
ESP_LOGE(m_tag, "Error sending Stratum setup commands!");
return;
}
// All Stratum servers should send the first job with clear flag,
// but we make sure to clear the jobs on the first job
m_firstJob = true;
char *line = nullptr;
while (1) {
if (!m_transport->isConnected()) {
if (Config::isStratumKeepaliveEnabled()) {
ESP_LOGW(m_tag, "Socket disconnected — possible TCP KeepAlive timeout (enabled)");
} else {
ESP_LOGW(m_tag, "Socket disconnected — no KeepAlive active");
}
break;
}
line = m_stratumAPI.receiveJsonRpcLine(m_transport);
// release memory when out of scope
MemoryGuard g(line);
if (!line && !m_reconnect) {
ESP_LOGE(m_tag, "Failed to receive JSON-RPC line, reconnecting ...");
return;
}
if (m_reconnect) {
ESP_LOGI(m_tag, "reconnect requested ...");
return;
}
ESP_LOGI(m_tag, "rx: %s", line); // debug incoming stratum messages
PSRAMAllocator allocator;
JsonDocument doc(&allocator);
// Deserialize JSON
// we want to know if it's valid json before the connected callback is executed
DeserializationError error = deserializeJson(doc, line);
if (error) {
ESP_LOGE(m_tag, "Unable to parse JSON: %s", error.c_str());
return;
}
// we are pretty confident now that we have valid json and we can
// call the connected callback
if (!m_isConnected) {
connectedCallback();
m_isConnected = true;
}
// if stop is requested, don't dispatch anything
// and break the loop
if (m_stopFlag || POWER_MANAGEMENT_MODULE.isShutdown()) {
return;
}
// parse the line
m_manager->dispatch(m_index, doc);
}
}
void StratumTaskV1::submitShare(const char *jobid, const char *extranonce_2, const uint32_t ntime, const uint32_t nonce,
const uint32_t version_rolled, const uint32_t version_base)
{
// V1 mining.submit expects version rolling bits (delta), not full version
uint32_t version_delta = version_rolled ^ version_base;
m_stratumAPI.submitShare(m_transport, m_config->getUser(), jobid, extranonce_2, ntime, nonce, version_delta);
}