-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEthereumPool.cs
More file actions
583 lines (448 loc) · 21.5 KB
/
Copy pathEthereumPool.cs
File metadata and controls
583 lines (448 loc) · 21.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
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using Autofac;
using AutoMapper;
using Microsoft.IO;
using Miningcore.Blockchain.Ethereum.Configuration;
using Miningcore.Configuration;
using Miningcore.Extensions;
using Miningcore.JsonRpc;
using Miningcore.Messaging;
using Miningcore.Mining;
using Miningcore.Nicehash;
using Miningcore.Notifications.Messages;
using Miningcore.Persistence;
using Miningcore.Persistence.Repositories;
using Miningcore.Stratum;
using Miningcore.Time;
using Newtonsoft.Json;
using static Miningcore.Util.ActionUtils;
namespace Miningcore.Blockchain.Ethereum;
[CoinFamily(CoinFamily.Ethereum)]
public class EthereumPool : PoolBase
{
public EthereumPool(IComponentContext ctx,
JsonSerializerSettings serializerSettings,
IConnectionFactory cf,
IStatsRepository statsRepo,
IMapper mapper,
IMasterClock clock,
IMessageBus messageBus,
RecyclableMemoryStreamManager rmsm,
NicehashService nicehashService) :
base(ctx, serializerSettings, cf, statsRepo, mapper, clock, messageBus, rmsm, nicehashService)
{
}
private EthereumJobManager manager;
private EthereumCoinTemplate coin;
private EthereumPoolConfigExtra extraPoolConfig;
#region // Protocol V2 handlers - https://github.com/nicehash/Specifications/blob/master/EthereumStratum_NiceHash_v1.0.0.txt
private async Task OnSubscribeAsync(StratumConnection connection, Timestamped<JsonRpcRequest> tsRequest)
{
var request = tsRequest.Value;
var context = connection.ContextAs<EthereumWorkerContext>();
if(request.Id == null)
throw new StratumException(StratumError.Other, "missing request id");
var requestParams = request.ParamsAs<string[]>();
if(requestParams == null || requestParams.Length < 2 || requestParams.Any(string.IsNullOrEmpty))
throw new StratumException(StratumError.MinusOne, "invalid request");
manager.PrepareWorker(connection);
context.UserAgent = requestParams.FirstOrDefault()?.Trim();
var data = new object[]
{
new object[]
{
EthereumStratumMethods.MiningNotify,
connection.ConnectionId,
EthereumConstants.EthereumStratumVersion
},
context.ExtraNonce1
}
.ToArray();
// Nicehash's stupid validator insists on "error" property present
// in successful responses which is a violation of the JSON-RPC spec
var response = new JsonRpcResponse<object[]>(data, request.Id);
if(context.IsNicehash)
{
response.Extra = new Dictionary<string, object>();
response.Extra["error"] = null;
}
await connection.RespondAsync(response);
// setup worker context
context.IsSubscribed = true;
}
private async Task OnAuthorizeAsync(StratumConnection connection, Timestamped<JsonRpcRequest> tsRequest)
{
var request = tsRequest.Value;
var context = connection.ContextAs<EthereumWorkerContext>();
if(request.Id == null)
throw new StratumException(StratumError.MinusOne, "missing request id");
var requestParams = request.ParamsAs<string[]>();
var workerValue = requestParams?.Length > 0 ? requestParams[0] : "0";
var password = requestParams?.Length > 1 ? requestParams[1] : null;
var passParts = password?.Split(PasswordControlVarsSeparator);
// extract worker/miner
var workerParts = workerValue?.Split('.');
var minerName = workerParts?.Length > 0 ? workerParts[0].Trim() : null;
var workerName = workerParts?.Length > 1 ? workerParts[1].Trim() : "0";
context.IsAuthorized = manager.ValidateAddress(minerName);
// respond
await connection.RespondAsync(context.IsAuthorized, request.Id);
if(context.IsAuthorized)
{
context.Miner = minerName?.ToLower();
context.Worker = workerName;
// extract control vars from password
var staticDiff = GetStaticDiffFromPassparts(passParts);
// Nicehash support
var nicehashDiff = await GetNicehashStaticMinDiff(context, coin.Name, coin.GetAlgorithmName());
if(nicehashDiff.HasValue)
{
if(!staticDiff.HasValue || nicehashDiff > staticDiff)
{
logger.Info(() => $"[{connection.ConnectionId}] Nicehash detected. Using API supplied difficulty of {nicehashDiff.Value}");
staticDiff = nicehashDiff;
}
else
logger.Info(() => $"[{connection.ConnectionId}] Nicehash detected. Using miner supplied difficulty of {staticDiff.Value}");
}
// Static diff
if(staticDiff.HasValue &&
(context.VarDiff != null && staticDiff.Value >= context.VarDiff.Config.MinDiff ||
context.VarDiff == null && staticDiff.Value > context.Difficulty))
{
context.VarDiff = null; // disable vardiff
context.SetDifficulty(staticDiff.Value);
logger.Info(() => $"[{connection.ConnectionId}] Setting static difficulty of {staticDiff.Value}");
}
await connection.NotifyAsync(EthereumStratumMethods.SetDifficulty, new object[] { context.Difficulty });
await connection.NotifyAsync(EthereumStratumMethods.MiningNotify, manager.GetJobParamsForStratum());
logger.Info(() => $"[{connection.ConnectionId}] Authorized worker {workerValue}");
}
else
{
if(clusterConfig?.Banning?.BanOnLoginFailure is null or true)
{
logger.Info(() => $"[{connection.ConnectionId}] Banning unauthorized worker {minerName} for {loginFailureBanTimeout.TotalSeconds} sec");
banManager.Ban(connection.RemoteEndpoint.Address, loginFailureBanTimeout);
Disconnect(connection);
}
}
}
private async Task OnSubmitAsync(StratumConnection connection, Timestamped<JsonRpcRequest> tsRequest, CancellationToken ct, bool v1 = false)
{
var request = tsRequest.Value;
var context = connection.ContextAs<EthereumWorkerContext>();
try
{
if(request.Id == null)
throw new StratumException(StratumError.MinusOne, "missing request id");
// check age of submission (aged submissions are usually caused by high server load)
var requestAge = clock.Now - tsRequest.Timestamp.UtcDateTime;
if(requestAge > maxShareAge)
{
logger.Warn(() => $"[{connection.ConnectionId}] Dropping stale share submission request (server overloaded?)");
return;
}
// validate worker
if(!context.IsAuthorized)
throw new StratumException(StratumError.UnauthorizedWorker, "unauthorized worker");
if(!context.IsSubscribed)
throw new StratumException(StratumError.NotSubscribed, "not subscribed");
// check request
var submitRequest = request.ParamsAs<string[]>();
if(submitRequest.Length != 3 ||
submitRequest.Any(string.IsNullOrEmpty))
throw new StratumException(StratumError.MinusOne, "malformed PoW result");
// recognize activity
context.LastActivity = clock.Now;
// submit
Share share;
if(!v1)
share = await manager.SubmitShareV2Async(connection, submitRequest, ct);
else
share = await manager.SubmitShareV1Async(connection, submitRequest, GetWorkerNameFromV1Request(request, context), ct);
await connection.RespondAsync(true, request.Id);
// publish
messageBus.SendMessage(share);
// telemetry
PublishTelemetry(TelemetryCategory.Share, clock.Now - tsRequest.Timestamp.UtcDateTime, true);
logger.Info(() => $"[{connection.ConnectionId}] Share accepted: D={Math.Round(share.Difficulty / EthereumConstants.Pow2x32, 3)}");
// update pool stats
if(share.IsBlockCandidate)
poolStats.LastPoolBlockTime = clock.Now;
// update client stats
context.Stats.ValidShares++;
await UpdateVarDiffAsync(connection, false, ct);
}
catch(StratumException ex)
{
// telemetry
PublishTelemetry(TelemetryCategory.Share, clock.Now - tsRequest.Timestamp.UtcDateTime, false);
// update client stats
context.Stats.InvalidShares++;
logger.Info(() => $"[{connection.ConnectionId}] Share rejected: {ex.Message} [{context.UserAgent}]");
// banning
ConsiderBan(connection, context, poolConfig.Banning);
throw;
}
}
private async Task SendJob(EthereumWorkerContext context, StratumConnection connection, object parameters)
{
// varDiff: if the client has a pending difficulty change, apply it now
if(context.ApplyPendingDifficulty())
await connection.NotifyAsync(EthereumStratumMethods.SetDifficulty, new object[] { context.Difficulty });
// send job
await connection.NotifyAsync(EthereumStratumMethods.MiningNotify, parameters);
}
#endregion // Protocol V2 handlers
#region // Protocol V1 handlers - https://github.com/sammy007/open-ethereum-pool/blob/master/docs/STRATUM.md
private async Task OnSubmitLoginAsync(StratumConnection connection, Timestamped<JsonRpcRequest> tsRequest)
{
var request = tsRequest.Value;
var context = connection.ContextAs<EthereumWorkerContext>();
if(request.Id == null)
throw new StratumException(StratumError.Other, "missing request id");
var requestParams = request.ParamsAs<string[]>();
if(requestParams?.Length < 1)
throw new StratumException(StratumError.MinusOne, "invalid request");
var workerValue = requestParams?.Length > 0 ? requestParams[0] : "0";
var password = requestParams?.Length > 1 ? requestParams[1] : null;
var passParts = password?.Split(PasswordControlVarsSeparator);
// extract worker/miner
var workerParts = workerValue?.Split('.');
var minerName = workerParts?.Length > 0 ? workerParts[0].Trim() : null;
var workerName = workerParts?.Length > 1 ? workerParts[1].Trim() : "0";
manager.PrepareWorker(connection);
context.IsAuthorized = manager.ValidateAddress(minerName);
// respond
await connection.RespondAsync(context.IsAuthorized, request.Id);
if(context.IsAuthorized)
{
context.Miner = minerName?.ToLower();
context.Worker = workerName;
// extract control vars from password
var staticDiff = GetStaticDiffFromPassparts(passParts);
// Nicehash support
var nicehashDiff = await GetNicehashStaticMinDiff(context, coin.Name, coin.GetAlgorithmName());
if(nicehashDiff.HasValue)
{
if(!staticDiff.HasValue || nicehashDiff > staticDiff)
{
logger.Info(() => $"[{connection.ConnectionId}] Nicehash detected. Using API supplied difficulty of {nicehashDiff.Value}");
staticDiff = nicehashDiff;
}
else
logger.Info(() => $"[{connection.ConnectionId}] Nicehash detected. Using miner supplied difficulty of {staticDiff.Value}");
}
// Static diff
if(staticDiff.HasValue &&
(context.VarDiff != null && staticDiff.Value >= context.VarDiff.Config.MinDiff ||
context.VarDiff == null && staticDiff.Value > context.Difficulty))
{
context.VarDiff = null; // disable vardiff
context.SetDifficulty(staticDiff.Value);
logger.Info(() => $"[{connection.ConnectionId}] Setting static difficulty of {staticDiff.Value}");
}
logger.Info(() => $"[{connection.ConnectionId}] Authorized worker {workerValue}");
// setup worker context
context.IsSubscribed = true;
}
else
{
if(clusterConfig?.Banning?.BanOnLoginFailure is null or true)
{
banManager.Ban(connection.RemoteEndpoint.Address, loginFailureBanTimeout);
logger.Info(() => $"[{connection.ConnectionId}] Banning unauthorized worker {minerName} for {loginFailureBanTimeout.TotalSeconds} sec");
Disconnect(connection);
}
}
}
private async Task OnGetWorkAsync(StratumConnection connection, Timestamped<JsonRpcRequest> tsRequest)
{
var request = tsRequest.Value;
var context = connection.ContextAs<EthereumWorkerContext>();
await SendWork(context, connection, request.Id);
}
private async Task SendWork(EthereumWorkerContext context, StratumConnection connection, object requestId)
{
var parameters = manager.GetWorkParamsForStratum(context);
// respond
await connection.RespondAsync(parameters, requestId);
}
#endregion // Protocol V1 handlers
#region Overrides
public override void Configure(PoolConfig pc, ClusterConfig cc)
{
coin = pc.Template.As<EthereumCoinTemplate>();
extraPoolConfig = pc.Extra.SafeExtensionDataAs<EthereumPoolConfigExtra>();
base.Configure(pc, cc);
}
protected override async Task SetupJobManager(CancellationToken ct)
{
manager = ctx.Resolve<EthereumJobManager>(
new TypedParameter(typeof(IExtraNonceProvider), new EthereumExtraNonceProvider(poolConfig.Id, clusterConfig.InstanceId)));
manager.Configure(poolConfig, clusterConfig);
await manager.StartAsync(ct);
if(poolConfig.EnableInternalStratum == true)
{
disposables.Add(manager.Jobs
.Select(_ => Observable.FromAsync(() =>
Guard(OnNewJobAsync,
ex=> logger.Debug(() => $"{nameof(OnNewJobAsync)}: {ex.Message}"))))
.Concat()
.Subscribe(_ => { }, ex =>
{
logger.Debug(ex, nameof(OnNewJobAsync));
}));
// start with initial blocktemplate
await manager.Jobs.Take(1).ToTask(ct);
}
else
{
// keep updating NetworkStats
disposables.Add(manager.Jobs.Subscribe());
}
}
protected override async Task InitStatsAsync(CancellationToken ct)
{
await base.InitStatsAsync(ct);
blockchainStats = manager.BlockchainStats;
}
protected override WorkerContextBase CreateWorkerContext()
{
return new EthereumWorkerContext();
}
private static string GetWorkerNameFromV1Request(JsonRpcRequest request, EthereumWorkerContext context)
{
if(request.Extra?.TryGetValue(EthereumConstants.RpcRequestWorkerPropertyName, out var tmp) == true && tmp is string workerNameValue)
return workerNameValue;
return context.Worker;
}
protected virtual async Task OnNewJobAsync()
{
var currentJobParams = manager.GetJobParamsForStratum();
logger.Info(() => $"Broadcasting job {currentJobParams[0]}");
await Guard(() => ForEachMinerAsync(async (connection, ct) =>
{
var context = connection.ContextAs<EthereumWorkerContext>();
switch(context.ProtocolVersion)
{
case 1:
await SendWork(context, connection, 0);
break;
case 2:
await SendJob(context, connection, currentJobParams);
break;
}
}));
}
protected void EnsureProtocolVersion(EthereumWorkerContext context, int version)
{
if(context.ProtocolVersion != version)
throw new StratumException(StratumError.MinusOne, $"protocol mismatch");
}
protected override async Task OnRequestAsync(StratumConnection connection,
Timestamped<JsonRpcRequest> tsRequest, CancellationToken ct)
{
var request = tsRequest.Value;
var context = connection.ContextAs<EthereumWorkerContext>();
try
{
switch(request.Method)
{
// V2/Nicehash Stratum Methods
case EthereumStratumMethods.Subscribe:
context.ProtocolVersion = 2; // lock in protocol version
await OnSubscribeAsync(connection, tsRequest);
break;
case EthereumStratumMethods.Authorize:
EnsureProtocolVersion(context, 2);
await OnAuthorizeAsync(connection, tsRequest);
break;
case EthereumStratumMethods.SubmitShare:
EnsureProtocolVersion(context, 2);
await OnSubmitAsync(connection, tsRequest, ct);
break;
case EthereumStratumMethods.ExtraNonceSubscribe:
EnsureProtocolVersion(context, 2);
// Pretend to support it even though we actually do not. Some miners drop the connection upon receiving an error from this
await connection.RespondAsync(true, request.Id);
break;
// V1 Stratum methods
// There are several reports of bad actors taking advantage of the old "Ethash Stratum V1" protocol in order to perform multiple dangerous attacks like man-in-the-middle (MITM) attacks
// https://braiins.com/blog/hashrate-robbery-stratum-v2-fixes-this-and-more
// https://eips.ethereum.org/EIPS/eip-1571
// https://github.com/AndreaLanfranchi/EthereumStratum-2.0.0/issues/10#issuecomment-595053258
// Based on that critical fact, mining pool should be cautious of the risks of using a such deprecated and broken stratum protocol. Used it at your own risks.
case EthereumStratumMethods.SubmitLogin:
context.ProtocolVersion = 1; // lock in protocol version
await OnSubmitLoginAsync(connection, tsRequest);
break;
case EthereumStratumMethods.GetWork:
if(!extraPoolConfig.enableEthashStratumV1)
{
logger.Info(() => $"[{connection.ConnectionId}] Unsupported RPC request: {JsonConvert.SerializeObject(request, serializerSettings)}");
await connection.RespondErrorAsync(StratumError.Other, $"Unsupported request {request.Method}", request.Id);
}
else
{
EnsureProtocolVersion(context, 1);
logger.Warn(() => $"Use of Ethash Stratum V1 method: {request.Method}");
await OnGetWorkAsync(connection, tsRequest);
}
break;
case EthereumStratumMethods.SubmitWork:
if(!extraPoolConfig.enableEthashStratumV1)
{
logger.Info(() => $"[{connection.ConnectionId}] Unsupported RPC request: {JsonConvert.SerializeObject(request, serializerSettings)}");
await connection.RespondErrorAsync(StratumError.Other, $"Unsupported request {request.Method}", request.Id);
}
else
{
EnsureProtocolVersion(context, 1);
logger.Warn(() => $"Use of Ethash Stratum V1 method: {request.Method}");
await OnSubmitAsync(connection, tsRequest, ct, true);
}
break;
case EthereumStratumMethods.SubmitHashrate:
await connection.RespondAsync(true, request.Id);
break;
default:
logger.Info(() => $"[{connection.ConnectionId}] Unsupported RPC request: {JsonConvert.SerializeObject(request, serializerSettings)}");
await connection.RespondErrorAsync(StratumError.Other, $"Unsupported request {request.Method}", request.Id);
break;
}
}
catch(StratumException ex)
{
await connection.RespondErrorAsync(ex.Code, ex.Message, request.Id, false);
}
}
public override double HashrateFromShares(double shares, double interval)
{
var result = shares / interval;
return result;
}
public override double ShareMultiplier => 1;
protected override async Task OnVarDiffUpdateAsync(StratumConnection connection, double newDiff, CancellationToken ct)
{
await base.OnVarDiffUpdateAsync(connection, newDiff, ct);
var context = connection.ContextAs<EthereumWorkerContext>();
if(context.HasPendingDifficulty)
{
switch(context.ProtocolVersion)
{
case 1:
context.ApplyPendingDifficulty();
await SendWork(context, connection, 0);
break;
case 2:
await SendJob(context, connection, manager.GetJobParamsForStratum());
break;
}
}
}
#endregion // Overrides
}