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

Commit

Permalink
fix: linter warnings and cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
jon4hz committed Feb 16, 2023
1 parent 7b6f393 commit 724780b
Show file tree
Hide file tree
Showing 8 changed files with 66 additions and 64 deletions.
4 changes: 3 additions & 1 deletion src/.idea/.idea.Miningcore/.idea/indexLayout.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

42 changes: 21 additions & 21 deletions src/Miningcore/Blockchain/Ravencoin/RavencoinJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,16 @@ namespace Miningcore.Blockchain.Ravencoin;

public class RavencoinJobParams
{
public ulong Height { get; set; }
public ulong Height { get; init; }
public bool CleanJobs { get; set; }
}

public class RavencoinJob : BitcoinJob
{
protected Cache kawpowHasher;
protected new RavencoinJobParams jobParams;
private Cache kawpowHasher;
private new RavencoinJobParams jobParams;

protected byte[] SerializeHeader(Span<byte> coinbaseHash)
private byte[] SerializeHeader(Span<byte> coinbaseHash)
{
// build merkle-root
var merkleRoot = mt.WithFirst(coinbaseHash.ToArray());
Expand All @@ -51,7 +51,7 @@ protected byte[] SerializeHeader(Span<byte> coinbaseHash)
return blockHeader.ToBytes();
}

public virtual (Share Share, string BlockHex) ProcessShareInternal(ILogger logger,
public (Share Share, string BlockHex) ProcessShareInternal(ILogger logger,
StratumConnection worker, ulong nonce, string inputHeaderHash, string mixHash)
{
var context = worker.ContextAs<RavencoinWorkerContext>();
Expand All @@ -68,7 +68,6 @@ public virtual (Share Share, string BlockHex) ProcessShareInternal(ILogger logge
headerHasher.Digest(headerBytes, headerHash);
headerHash.Reverse();

var headerValue = new uint256(headerHash);
var headerHashHex = headerHash.ToHexString();

if(headerHashHex != inputHeaderHash)
Expand Down Expand Up @@ -119,25 +118,25 @@ public virtual (Share Share, string BlockHex) ProcessShareInternal(ILogger logge
Difficulty = stratumDifficulty / shareMultiplier,
};

if(isBlockCandidate)
if(!isBlockCandidate)
{
result.IsBlockCandidate = true;
result.BlockHash = resultBytes.ReverseInPlace().ToHexString();
return (result, null);
}

var blockBytes = SerializeBlock(headerBytes, coinbase, nonce, mixHashOut);
var blockHex = blockBytes.ToHexString();
result.IsBlockCandidate = true;
result.BlockHash = resultBytes.ReverseInPlace().ToHexString();

return (result, blockHex);
}
var blockBytes = SerializeBlock(headerBytes, coinbase, nonce, mixHashOut);
var blockHex = blockBytes.ToHexString();

return (result, null);
return (result, blockHex);
}

protected virtual byte[] SerializeCoinbase(string extraNonce1)
private byte[] SerializeCoinbase(string extraNonce1)
{
var extraNonce1Bytes = extraNonce1.HexToByteArray();

using(var stream = new MemoryStream())
using var stream = new MemoryStream();
{
stream.Write(coinbaseInitial);
stream.Write(extraNonce1Bytes);
Expand All @@ -147,12 +146,12 @@ protected virtual byte[] SerializeCoinbase(string extraNonce1)
}
}

protected virtual byte[] SerializeBlock(byte[] header, byte[] coinbase, ulong nonce, byte[] mixHash)
private byte[] SerializeBlock(byte[] header, byte[] coinbase, ulong nonce, byte[] mixHash)
{
var rawTransactionBuffer = BuildRawTransactionBuffer();
var transactionCount = (uint) BlockTemplate.Transactions.Length + 1; // +1 for prepended coinbase tx

using(var stream = new MemoryStream())
using var stream = new MemoryStream();
{
var bs = new BitcoinStream(stream, true);

Expand Down Expand Up @@ -198,7 +197,8 @@ public void Init(BlockTemplate blockTemplate, string jobId,
var coinbaseString = !string.IsNullOrEmpty(cc.PaymentProcessing?.CoinbaseString) ?
cc.PaymentProcessing?.CoinbaseString.Trim() : "Miningcore";

this.scriptSigFinalBytes = new Script(Op.GetPushOp(Encoding.UTF8.GetBytes(coinbaseString))).ToBytes();
if(!string.IsNullOrEmpty(coinbaseString))
this.scriptSigFinalBytes = new Script(Op.GetPushOp(Encoding.UTF8.GetBytes(coinbaseString))).ToBytes();

this.Difficulty = new Target(System.Numerics.BigInteger.Parse(BlockTemplate.Target, NumberStyles.HexNumber)).Difficulty;

Expand Down Expand Up @@ -233,7 +233,7 @@ public void Init(BlockTemplate blockTemplate, string jobId,
return jobParams;
}

public virtual void PrepareWorkerJob(RavencoinWorkerJob workerJob, out string headerHash)
public void PrepareWorkerJob(RavencoinWorkerJob workerJob, out string headerHash)
{
workerJob.Job = this;
workerJob.Height = BlockTemplate.Height;
Expand All @@ -242,7 +242,7 @@ public virtual void PrepareWorkerJob(RavencoinWorkerJob workerJob, out string he
headerHash = CreateHeaderHash(workerJob);
}

protected virtual string CreateHeaderHash(RavencoinWorkerJob workerJob)
private string CreateHeaderHash(RavencoinWorkerJob workerJob)
{
var headerHasher = coin.HeaderHasherValue;
var coinbaseHasher = coin.CoinbaseHasherValue;
Expand Down
40 changes: 21 additions & 19 deletions src/Miningcore/Blockchain/Ravencoin/RavencoinJobManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,38 +29,38 @@ public RavencoinJobManager(

private RavencoinTemplate coin;

protected async Task<RpcResponse<BlockTemplate>> GetBlockTemplateAsync(CancellationToken ct)
private async Task<RpcResponse<BlockTemplate>> GetBlockTemplateAsync(CancellationToken ct)
{
var result = await rpc.ExecuteAsync<BlockTemplate>(logger,
BitcoinCommands.GetBlockTemplate, ct, extraPoolConfig?.GBTArgs ?? (object) GetBlockTemplateParams());

return result;
}

protected RpcResponse<BlockTemplate> GetBlockTemplateFromJson(string json)
private RpcResponse<BlockTemplate> GetBlockTemplateFromJson(string json)
{
var result = JsonConvert.DeserializeObject<JsonRpcResponse>(json);

return new RpcResponse<BlockTemplate>(result!.ResultAs<BlockTemplate>());
}

private RavencoinJob CreateJob()
private static RavencoinJob CreateJob()
{
return new();
return new RavencoinJob();
}

public double ShareMultiplier => coin.ShareMultiplier;
private double ShareMultiplier => coin.ShareMultiplier;


protected override void PostChainIdentifyConfigure()
{
base.PostChainIdentifyConfigure();

if(poolConfig.EnableInternalStratum == true && coin.HeaderHasherValue is IHashAlgorithmInit hashInit)
{
if(!hashInit.DigestInit(poolConfig))
logger.Error(() => $"{hashInit.GetType().Name} initialization failed");
}
if(poolConfig.EnableInternalStratum == false || coin.HeaderHasherValue is not IHashAlgorithmInit hashInit)
return;

if(!hashInit.DigestInit(poolConfig))
logger.Error(() => $"{hashInit.GetType().Name} initialization failed");
}

protected override async Task PostStartInitAsync(CancellationToken ct)
Expand All @@ -74,7 +74,7 @@ protected override async Task PostStartInitAsync(CancellationToken ct)
{
var blockTemplate = await GetBlockTemplateAsync(ct);

if(blockTemplate != null || blockTemplate.Response != null)
if(blockTemplate?.Response != null)
{
logger.Info(() => "Loading current light cache ...");

Expand Down Expand Up @@ -123,7 +123,9 @@ await GetBlockTemplateAsync(ct) :
{
job = CreateJob();

var kawpowHasher = await coin.KawpowHasher.GetCacheAsync(logger, (int) blockTemplate.Height);
var blockHeight = blockTemplate?.Height ?? currentJob.BlockTemplate.Height;

var kawpowHasher = await coin.KawpowHasher.GetCacheAsync(logger, (int) blockHeight);

job.Init(blockTemplate, NextJobId(),
poolConfig, extraPoolConfig, clusterConfig, clock, poolAddressDestination, network, isPoS,
Expand Down Expand Up @@ -198,7 +200,7 @@ public override void Configure(PoolConfig pc, ClusterConfig cc)
base.Configure(pc, cc);
}

public virtual object[] GetSubscriberData(StratumConnection worker)
public object[] GetSubscriberData(StratumConnection worker)
{
Contract.RequiresNonNull(worker);

Expand All @@ -216,7 +218,7 @@ public virtual object[] GetSubscriberData(StratumConnection worker)
return responseData;
}

public virtual void PrepareWorkerJob(RavencoinWorkerJob workerJob, out string headerHash)
public void PrepareWorkerJob(RavencoinWorkerJob workerJob, out string headerHash)
{
headerHash = null;

Expand All @@ -231,7 +233,7 @@ public virtual void PrepareWorkerJob(RavencoinWorkerJob workerJob, out string he
}
}

public virtual async ValueTask<Share> SubmitShareAsync(StratumConnection worker, object submission,
public async ValueTask<Share> SubmitShareAsync(StratumConnection worker, object submission,
CancellationToken ct)
{
Contract.RequiresNonNull(worker);
Expand All @@ -245,9 +247,9 @@ public virtual async ValueTask<Share> SubmitShareAsync(StratumConnection worker,
// extract params
var workerValue = (submitParams[0] as string)?.Trim();
var jobId = submitParams[1] as string;
var nonce = (submitParams[2] as string).Substring(2);
var headerHash = (submitParams[3] as string).Substring(2);
var mixHash = (submitParams[4] as string).Substring(2);
var nonce = (submitParams[2] as string)?.Substring(2);
var headerHash = (submitParams[3] as string)?.Substring(2);
var mixHash = (submitParams[4] as string)?.Substring(2);

if(string.IsNullOrEmpty(workerValue))
throw new StratumException(StratumError.Other, "missing or invalid workername");
Expand Down Expand Up @@ -308,4 +310,4 @@ public virtual async ValueTask<Share> SubmitShareAsync(StratumConnection worker,
}

#endregion // API-Surface
}
}
18 changes: 8 additions & 10 deletions src/Miningcore/Blockchain/Ravencoin/RavencoinPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ public RavencoinPool(IComponentContext ctx,
{
}

protected RavencoinJobParams currentJobParams;
private RavencoinJobParams currentJobParams;
private long currentJobId;
protected RavencoinJobManager manager;
private RavencoinJobManager manager;
private RavencoinTemplate coin;

protected virtual async Task OnSubscribeAsync(StratumConnection connection, Timestamped<JsonRpcRequest> tsRequest)
Expand Down Expand Up @@ -80,7 +80,7 @@ protected virtual async Task OnSubscribeAsync(StratumConnection connection, Time
context.SetDifficulty(nicehashDiff.Value);
}

var minerJobParams = CreateWorkerJob(connection, (int) currentJobParams.Height, currentJobParams.CleanJobs);
var minerJobParams = CreateWorkerJob(connection, currentJobParams.CleanJobs);
// send intial update
await connection.NotifyAsync(RavencoinStratumMethods.SetDifficulty, new object[] { RavencoinUtils.EncodeTarget(context.Difficulty) });
await connection.NotifyAsync(RavencoinStratumMethods.MiningNotify, minerJobParams);
Expand Down Expand Up @@ -150,7 +150,7 @@ protected virtual async Task OnAuthorizeAsync(StratumConnection connection, Time
}
}

private object CreateWorkerJob(StratumConnection connection, int block, bool update)
private object CreateWorkerJob(StratumConnection connection, bool update)
{
var context = connection.ContextAs<RavencoinWorkerContext>();
var job = new RavencoinWorkerJob(NextJobId(), context.ExtraNonce1);
Expand Down Expand Up @@ -256,11 +256,11 @@ protected virtual async Task OnNewJobAsync(object job)

currentJobParams = job as RavencoinJobParams;

await Guard(() => ForEachMinerAsync(async (connection, ct) =>
await Guard(() => ForEachMinerAsync(async (connection, _) =>
{
var context = connection.ContextAs<RavencoinWorkerContext>();
var minerJobParams = CreateWorkerJob(connection, (int) currentJobParams.Height, currentJobParams.CleanJobs);
var minerJobParams = CreateWorkerJob(connection, currentJobParams.CleanJobs);
if(context.ApplyPendingDifficulty())
await connection.NotifyAsync(RavencoinStratumMethods.SetDifficulty, new object[] { RavencoinUtils.EncodeTarget(context.Difficulty) });
Expand Down Expand Up @@ -385,13 +385,11 @@ protected override async Task OnVarDiffUpdateAsync(StratumConnection connection,

if(connection.Context.ApplyPendingDifficulty())
{
var context = connection.ContextAs<RavencoinWorkerContext>();
var minerJobParams = CreateWorkerJob(connection, (int) currentJobParams.Height, currentJobParams.CleanJobs);

var minerJobParams = CreateWorkerJob(connection, currentJobParams.CleanJobs);
await connection.NotifyAsync(RavencoinStratumMethods.SetDifficulty, new object[] { RavencoinUtils.EncodeTarget(connection.Context.Difficulty) });
await connection.NotifyAsync(RavencoinStratumMethods.MiningNotify, minerJobParams);
}
}

#endregion // Overrides
}
}
10 changes: 5 additions & 5 deletions src/Miningcore/Blockchain/Ravencoin/RavencoinWorkerContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,18 @@ public class RavencoinWorkerContext : WorkerContextBase
/// </summary>
public string ExtraNonce1 { get; set; }

private List<RavencoinWorkerJob> validJobs { get; } = new();
private List<RavencoinWorkerJob> ValidJobs { get; } = new();

public void AddJob(RavencoinWorkerJob job)
{
validJobs.Insert(0, job);
ValidJobs.Insert(0, job);

while(validJobs.Count > 4)
validJobs.RemoveAt(validJobs.Count - 1);
while(ValidJobs.Count > 4)
ValidJobs.RemoveAt(ValidJobs.Count - 1);
}

public RavencoinWorkerJob FindJob(string jobId)
{
return validJobs.FirstOrDefault(x => x.Id == jobId);
return ValidJobs.FirstOrDefault(x => x.Id == jobId);
}
}
10 changes: 5 additions & 5 deletions src/Miningcore/Blockchain/Ravencoin/RavencoinWorkerJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public RavencoinWorkerJob(string jobId, string extraNonce1)
public string Bits { get; set; }
public string SeedHash { get; set; }

public readonly ConcurrentDictionary<string, bool> Submissions = new(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<string, bool> submissions = new(StringComparer.OrdinalIgnoreCase);

private bool RegisterSubmit(string nonce, string headerHash, string mixHash)
{
Expand All @@ -32,10 +32,10 @@ private bool RegisterSubmit(string nonce, string headerHash, string mixHash)
.Append(mixHash)
.ToString();

return Submissions.TryAdd(key, true);
return submissions.TryAdd(key, true);
}

public virtual (Share Share, string BlockHex) ProcessShare(ILogger logger, StratumConnection worker, string nonce, string headerHash, string mixHash)
public (Share Share, string BlockHex) ProcessShare(ILogger logger, StratumConnection worker, string nonce, string headerHash, string mixHash)
{
Contract.RequiresNonNull(worker);
Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(nonce));
Expand All @@ -51,7 +51,7 @@ public virtual (Share Share, string BlockHex) ProcessShare(ILogger logger, Strat
throw new StratumException(StratumError.Other, $"incorrect size of nonce: {nonce}");

// check if nonce is within range
if(nonce.IndexOf(context.ExtraNonce1.Substring(0, 4)) != 0)
if(nonce.IndexOf(context.ExtraNonce1[0..4], StringComparison.OrdinalIgnoreCase) != 0)
throw new StratumException(StratumError.Other, $"nonce out of range: {nonce}");

// dupe check
Expand All @@ -62,4 +62,4 @@ public virtual (Share Share, string BlockHex) ProcessShare(ILogger logger, Strat

return Job.ProcessShareInternal(logger, worker, nonceLong, headerHash, mixHash);
}
}
}
4 changes: 2 additions & 2 deletions src/Miningcore/Crypto/Hashing/Algorithms/Sha256DT.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ public void Digest(ReadOnlySpan<byte> data, Span<byte> result, params object[] e
{
Contract.Requires<ArgumentException>(result.Length >= 32);

fixed (byte* input = data)
fixed(byte* input = data)
{
fixed (byte* output = result)
fixed(byte* output = result)
{
Multihash.sha256dt(input, output);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Miningcore/coins.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"telegram": "https://t.me/VGC_5GCASH",
"discord": "https://discord.gg/uXHvyBT",
"coinbaseHasher": {
"hash": "sha256d"
"hash": "sha256d",
},
"headerHasher": {
"hash": "x16r-v2"
Expand Down

0 comments on commit 724780b

Please sign in to comment.