58 lines
1.7 KiB
C#
58 lines
1.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Security.Cryptography;
|
|
using System.Threading.Tasks;
|
|
using System.Text.Json.Serialization;
|
|
|
|
namespace WpfBlockChanApp
|
|
{
|
|
internal class Block
|
|
{
|
|
public int Index { get; set; }
|
|
public string PreviousHash { get; set; }
|
|
public string Hash { get; set; }
|
|
public string Data { get; set; }
|
|
public long Timestamp { get; set; }
|
|
public int Nonce { get; set; }
|
|
public int Difficulty { get; set; }
|
|
public int LastAdjustBlock { get; set; }
|
|
|
|
[JsonIgnore]
|
|
public string GetString
|
|
{
|
|
get { return $"{Index}\n{Data}\n{PreviousHash}\n{Hash}"; }
|
|
}
|
|
|
|
public Block(int index, string previousHash, string data, int difficulty, int lastAdjustBlock)
|
|
{
|
|
Index = index;
|
|
PreviousHash = previousHash;
|
|
Data = data;
|
|
Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
|
Nonce = 0;
|
|
Difficulty = difficulty;
|
|
LastAdjustBlock = lastAdjustBlock;
|
|
Hash = CalculateHash();
|
|
}
|
|
|
|
public string CalculateHash()
|
|
{
|
|
using (SHA256 sha256 = SHA256.Create())
|
|
{
|
|
byte[] inputBytes = Encoding.UTF8.GetBytes($"{Index}{PreviousHash}{Timestamp}{Data}{Difficulty}{Nonce}");
|
|
byte[] outputBytes = sha256.ComputeHash(inputBytes);
|
|
return Convert.ToBase64String(outputBytes);
|
|
}
|
|
}
|
|
|
|
public bool MatchDifficulty()
|
|
{
|
|
return Hash[..Difficulty] != new string('0', Difficulty);
|
|
}
|
|
|
|
|
|
}
|
|
}
|