Skip to content
This repository has been archived by the owner on Oct 20, 2023. It is now read-only.

Ethash Abstraction #1594

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 21 additions & 8 deletions src/Miningcore/AutofacModule.cs
Original file line number Diff line number Diff line change
@@ -1,29 +1,30 @@
using System.Reflection;
using Autofac;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IO;
using Miningcore.Api;
using Miningcore.Banning;
using Miningcore.Blockchain.Bitcoin;
using Miningcore.Blockchain.Conceal;
using Miningcore.Blockchain.Cryptonote;
using Miningcore.Blockchain.Equihash;
using Miningcore.Blockchain.Ergo;
using Miningcore.Blockchain.Ethereum;
using Miningcore.Configuration;
using Miningcore.Crypto;
using Miningcore.Crypto.Hashing.Equihash;
using Miningcore.Crypto.Hashing.Ethash;
using Miningcore.Messaging;
using Miningcore.Mining;
using Miningcore.Nicehash;
using Miningcore.Notifications;
using Miningcore.Payments;
using Miningcore.Payments.PaymentSchemes;
using Miningcore.Pushover;
using Miningcore.Time;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Module = Autofac.Module;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IO;
using Miningcore.Blockchain.Ergo;
using Miningcore.Nicehash;
using Miningcore.Pushover;

namespace Miningcore;

Expand Down Expand Up @@ -78,7 +79,19 @@ protected override void Load(ContainerBuilder builder)
builder.RegisterAssemblyTypes(ThisAssembly)
.Where(t => t.GetCustomAttributes<IdentifierAttribute>().Any() &&
t.GetInterfaces().Any(i => i.IsAssignableFrom(typeof(IHashAlgorithm))))
.Named<IHashAlgorithm>(t=> t.GetCustomAttributes<IdentifierAttribute>().First().Name)
.Named<IHashAlgorithm>(t => t.GetCustomAttributes<IdentifierAttribute>().First().Name)
.PropertiesAutowired();

builder.RegisterAssemblyTypes(ThisAssembly)
.Where(t => t.GetCustomAttributes<IdentifierAttribute>().Any() &&
t.GetInterfaces().Any(i => i.IsAssignableFrom(typeof(IEthashFull))))
.Named<IEthashFull>(t => t.GetCustomAttributes<IdentifierAttribute>().First().Name)
.PropertiesAutowired();

builder.RegisterAssemblyTypes(ThisAssembly)
.Where(t => t.GetCustomAttributes<IdentifierAttribute>().Any() &&
t.GetInterfaces().Any(i => i.IsAssignableFrom(typeof(IEthashDag))))
.Named<IEthashDag>(t => t.GetCustomAttributes<IdentifierAttribute>().First().Name)
.PropertiesAutowired();

builder.RegisterAssemblyTypes(ThisAssembly)
Expand Down Expand Up @@ -148,12 +161,12 @@ protected override void Load(ContainerBuilder builder)
// Bitcoin and family

builder.RegisterType<BitcoinJobManager>();

//////////////////////
// Conceal

builder.RegisterType<ConcealJobManager>();

//////////////////////
// Cryptonote

Expand Down
4 changes: 2 additions & 2 deletions src/Miningcore/Blockchain/Conceal/ConcealPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ protected override async Task SetupJobManager(CancellationToken ct)
disposables.Add(manager.Blocks
.Select(_ => Observable.FromAsync(() =>
Guard(OnNewJobAsync,
ex=> logger.Debug(() => $"{nameof(OnNewJobAsync)}: {ex.Message}"))))
ex => logger.Debug(() => $"{nameof(OnNewJobAsync)}: {ex.Message}"))))
.Concat()
.Subscribe(_ => { }, ex =>
{
Expand All @@ -338,7 +338,7 @@ private string GetMinerAlgo()
{
case CryptonightHashType.CryptonightCCX:
return $"cn-ccx";

case CryptonightHashType.CryptonightGPU:
return $"cn-gpu";
}
Expand Down
156 changes: 5 additions & 151 deletions src/Miningcore/Blockchain/Ethereum/EthereumJob.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using System.Globalization;
using System.Numerics;
using Miningcore.Crypto.Hashing.Etchash;
using Miningcore.Crypto.Hashing.Ethash;
using Miningcore.Crypto.Hashing.Ubqhash;
using Miningcore.Extensions;
using Miningcore.Stratum;
using NBitcoin;
Expand All @@ -12,11 +10,12 @@ namespace Miningcore.Blockchain.Ethereum;

public class EthereumJob
{
public EthereumJob(string id, EthereumBlockTemplate blockTemplate, ILogger logger)
public EthereumJob(string id, EthereumBlockTemplate blockTemplate, ILogger logger, IEthashFull ethashFull)
{
Id = id;
BlockTemplate = blockTemplate;
this.logger = logger;
this.ethashFull = ethashFull;

var target = blockTemplate.Target;
if(target.StartsWith("0x"))
Expand All @@ -31,6 +30,7 @@ public EthereumJob(string id, EthereumBlockTemplate blockTemplate, ILogger logge
public EthereumBlockTemplate BlockTemplate { get; }
private readonly uint256 blockTarget;
private readonly ILogger logger;
private readonly IEthashFull ethashFull;

public record SubmitResult(Share Share, string FullNonceHex = null, string HeaderHash = null, string MixHash = null);

Expand All @@ -52,155 +52,9 @@ private void RegisterNonce(StratumConnection worker, string nonce)
nonces.Add(nonceLower);
}
}

public async Task<SubmitResult> ProcessShareEtcHashAsync(StratumConnection worker,
string workerName, string fullNonceHex, EtchashFull etchash, CancellationToken ct)
{
// dupe check
lock(workerNonces)
{
RegisterNonce(worker, fullNonceHex);
}

var context = worker.ContextAs<EthereumWorkerContext>();

if(!ulong.TryParse(fullNonceHex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var fullNonce))
throw new StratumException(StratumError.MinusOne, "bad nonce " + fullNonceHex);

// get dag for block
var dag = await etchash.GetDagAsync(BlockTemplate.Height, logger, CancellationToken.None);

// compute
if(!dag.Compute(logger, BlockTemplate.Header.HexToByteArray(), fullNonce, out var mixDigest, out var resultBytes))
throw new StratumException(StratumError.MinusOne, "bad hash");

// test if share meets at least workers current difficulty
resultBytes.ReverseInPlace();
var resultValue = new uint256(resultBytes);
var resultValueBig = resultBytes.AsSpan().ToBigInteger();
var shareDiff = (double) BigInteger.Divide(EthereumConstants.BigMaxValue, resultValueBig) / EthereumConstants.Pow2x32;
var stratumDifficulty = context.Difficulty;
var ratio = shareDiff / stratumDifficulty;
var isBlockCandidate = resultValue <= blockTarget;

if(!isBlockCandidate && ratio < 0.99)
{
// check if share matched the previous difficulty from before a vardiff retarget
if(context.VarDiff?.LastUpdate != null && context.PreviousDifficulty.HasValue)
{
ratio = shareDiff / context.PreviousDifficulty.Value;

if(ratio < 0.99)
throw new StratumException(StratumError.LowDifficultyShare, $"low difficulty share ({shareDiff})");

// use previous difficulty
stratumDifficulty = context.PreviousDifficulty.Value;
}

else
throw new StratumException(StratumError.LowDifficultyShare, $"low difficulty share ({shareDiff})");
}

var share = new Share
{
BlockHeight = (long) BlockTemplate.Height,
IpAddress = worker.RemoteEndpoint?.Address?.ToString(),
Miner = context.Miner,
Worker = workerName,
UserAgent = context.UserAgent,
IsBlockCandidate = isBlockCandidate,
Difficulty = stratumDifficulty * EthereumConstants.Pow2x32
};

if(share.IsBlockCandidate)
{
fullNonceHex = "0x" + fullNonceHex;
var headerHash = BlockTemplate.Header;
var mixHash = mixDigest.ToHexString(true);

share.TransactionConfirmationData = "";

return new SubmitResult(share, fullNonceHex, headerHash, mixHash);
}

return new SubmitResult(share);
}

public async Task<SubmitResult> ProcessShareAsync(StratumConnection worker,
string workerName, string fullNonceHex, EthashFull ethash, CancellationToken ct)
{
// dupe check
lock(workerNonces)
{
RegisterNonce(worker, fullNonceHex);
}

var context = worker.ContextAs<EthereumWorkerContext>();

if(!ulong.TryParse(fullNonceHex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var fullNonce))
throw new StratumException(StratumError.MinusOne, "bad nonce " + fullNonceHex);

// get dag for block
var dag = await ethash.GetDagAsync(BlockTemplate.Height, logger, CancellationToken.None);

// compute
if(!dag.Compute(logger, BlockTemplate.Header.HexToByteArray(), fullNonce, out var mixDigest, out var resultBytes))
throw new StratumException(StratumError.MinusOne, "bad hash");

// test if share meets at least workers current difficulty
resultBytes.ReverseInPlace();
var resultValue = new uint256(resultBytes);
var resultValueBig = resultBytes.AsSpan().ToBigInteger();
var shareDiff = (double) BigInteger.Divide(EthereumConstants.BigMaxValue, resultValueBig) / EthereumConstants.Pow2x32;
var stratumDifficulty = context.Difficulty;
var ratio = shareDiff / stratumDifficulty;
var isBlockCandidate = resultValue <= blockTarget;

if(!isBlockCandidate && ratio < 0.99)
{
// check if share matched the previous difficulty from before a vardiff retarget
if(context.VarDiff?.LastUpdate != null && context.PreviousDifficulty.HasValue)
{
ratio = shareDiff / context.PreviousDifficulty.Value;

if(ratio < 0.99)
throw new StratumException(StratumError.LowDifficultyShare, $"low difficulty share ({shareDiff})");

// use previous difficulty
stratumDifficulty = context.PreviousDifficulty.Value;
}

else
throw new StratumException(StratumError.LowDifficultyShare, $"low difficulty share ({shareDiff})");
}

var share = new Share
{
BlockHeight = (long) BlockTemplate.Height,
IpAddress = worker.RemoteEndpoint?.Address?.ToString(),
Miner = context.Miner,
Worker = workerName,
UserAgent = context.UserAgent,
IsBlockCandidate = isBlockCandidate,
Difficulty = stratumDifficulty * EthereumConstants.Pow2x32
};

if(share.IsBlockCandidate)
{
fullNonceHex = "0x" + fullNonceHex;
var headerHash = BlockTemplate.Header;
var mixHash = mixDigest.ToHexString(true);

share.TransactionConfirmationData = "";

return new SubmitResult(share, fullNonceHex, headerHash, mixHash);
}

return new SubmitResult(share);
}

public async Task<SubmitResult> ProcessShareUbqHashAsync(StratumConnection worker,
string workerName, string fullNonceHex, UbqhashFull ubqhash, CancellationToken ct)
string workerName, string fullNonceHex, CancellationToken ct)
{
// dupe check
lock(workerNonces)
Expand All @@ -214,7 +68,7 @@ public async Task<SubmitResult> ProcessShareUbqHashAsync(StratumConnection worke
throw new StratumException(StratumError.MinusOne, "bad nonce " + fullNonceHex);

// get dag for block
var dag = await ubqhash.GetDagAsync(BlockTemplate.Height, logger, CancellationToken.None);
var dag = await ethashFull.GetDagAsync(BlockTemplate.Height, logger, CancellationToken.None);

// compute
if(!dag.Compute(logger, BlockTemplate.Header.HexToByteArray(), fullNonce, out var mixDigest, out var resultBytes))
Expand Down
Loading