我们首先添加一个新的方法来验证生成的散列值是否包含指定数量的前导 0 :
- /// <summary>
- /// 校验 Hash 是否有效
- /// </summary>
- /// <param name="hashStr">Hash 值</param>
- /// <param name="difficulty">难度</param>
- /// <returns></returns>
- public static bool IsHashValid(string hashStr, int difficulty)
- {
- var bytes = Enumerable.Range(0, hashStr.Length)
- .Where(n => n % 2 == 0)
- .Select(n => Convert.ToByte(hashStr.Substring(n, 2), 16))
- .ToArray();
- var bits = new BitArray(bytes);
- for (var i = 0; i < difficulty; i++)
- {
- if (bits[i]) return false;
- }
- return true;
- }
然后我们更改了之前区块 Hash 的生成方法:
- /// <summary>
- /// 计算区块 HASH 值
- /// </summary>
- /// <param name="block">区块实例</param>
- /// <returns>计算完成的区块散列值</returns>
- public static string CalculateHash(Block block)
- {
- string calculationStr = $"{block.Index}{block.TimeStamp}{block.BPM}{block.PrevHash}{block.Nonce}";
- SHA256 sha256Generator = SHA256.Create();
- byte[] sha256HashBytes = sha256Generator.ComputeHash(Encoding.UTF8.GetBytes(calculationStr));
- StringBuilder sha256StrBuilder = new StringBuilder();
- foreach (byte @byte in sha256HashBytes)
- {
- sha256StrBuilder.Append(@byte.ToString("x2"));
- }
- return sha256StrBuilder.ToString();
- }
在这里我们新增新增了 Nonce 随机值作为散列生成的依据。
那么我们生成新区块的时候就顺便来挖矿吧:
- /// <summary>
- /// 生成新的区块
- /// </summary>
- /// <param name="oldBlock">旧的区块数据</param>
- /// <param name="BPM">心率</param>
- /// <returns>新的区块</returns>
- public static Block GenerateBlock(Block oldBlock, int BPM)
- {
- Block newnewBlock = new Block()
- {
- Index = oldBlock.Index + 1,
- TimeStamp = CalculateCurrentTimeUTC(),
- BPMBPM = BPM,
- PrevHash = oldBlock.Hash,
- DifficultyDifficulty = Difficulty
- };
- // 挖矿 ing...
- for (int i = 0; ; i++)
- {
- newBlock.Nonce = i.ToString("x2");
- if (!IsHashValid(CalculateHash(newBlock), Difficulty))
- {
- Console.WriteLine($"目前结果:{CalculateHash(newBlock)} ,正在计算中...");
- Task.Delay(1);
- continue;
- }
- else
- {
- Console.WriteLine($"目前结果:{CalculateHash(newBlock)} ,计算完毕...");
- newBlock.Hash = CalculateHash(newBlock);
- break;
- }
- }
- // 原有代码
- // newBlock.Hash = CalculateHash(newBlock);
- return newBlock;
- }
(编辑:云计算网_泰州站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|