diff --git a/BasicBlockChain/Block.cs b/BasicBlockChain/Block.cs index 27c186b..1d71359 100644 --- a/BasicBlockChain/Block.cs +++ b/BasicBlockChain/Block.cs @@ -11,6 +11,7 @@ namespace BasicBlockChain public string PreviousHash { get; set; } public string Data { get; set; } public string Hash { get; set; } + public int Nonce { get; set; } public Block(DateTime date, Block previousBlock, string data) { @@ -25,11 +26,21 @@ namespace BasicBlockChain { SHA256 sha256 = SHA256.Create(); - byte[] dataBytes = Encoding.UTF8.GetBytes(string.Format("{0}-{1}-{2}", Date, PreviousHash, Data)); + byte[] dataBytes = Encoding.UTF8.GetBytes(string.Format("{0}-{1}-{2}-{3}", Date, PreviousHash, Data, Nonce)); byte[] hashBytes = sha256.ComputeHash(dataBytes); string hash = Convert.ToBase64String(hashBytes); return hash; } + + public void Mine(int difficulty) + { + var leadingZeros = new string('0', difficulty); + while (Hash.Substring(0, difficulty) != leadingZeros) + { + Nonce++; + Hash = CalculateHash(); + } + } } } diff --git a/BasicBlockChain/BlockChain.cs b/BasicBlockChain/BlockChain.cs index 6b472b5..69e1a34 100644 --- a/BasicBlockChain/BlockChain.cs +++ b/BasicBlockChain/BlockChain.cs @@ -7,10 +7,13 @@ namespace BasicBlockChain public class BlockChain { public List Chain { get; } = new List(); + public int Difficulty { get; set; } = 2; - public BlockChain(DateTime? genesisDate = null) + public BlockChain(DateTime? genesisDate = null, int difficulty = 2) { Block genesisBlock = new Block(genesisDate ?? DateTime.UtcNow, null, "{}"); + genesisBlock.Mine(difficulty); + Difficulty = difficulty; Chain.Add(genesisBlock); } @@ -18,6 +21,7 @@ namespace BasicBlockChain { Block lastBlock = Chain.Last(); Block newBlock = new Block(date, lastBlock, data); + newBlock.Mine(Difficulty); Chain.Add(newBlock); } diff --git a/BasicBlockChain/Program.cs b/BasicBlockChain/Program.cs index a895bc9..42c4dd2 100644 --- a/BasicBlockChain/Program.cs +++ b/BasicBlockChain/Program.cs @@ -10,12 +10,15 @@ namespace BasicBlockChain // Example BlockChain with some example data Console.WriteLine(); - Console.WriteLine("#### BlockChain with sample data"); - BlockChain nullCoin = new BlockChain(new DateTime(2000, 1, 1)); + Console.WriteLine("#### Mining BlockChain with sample data"); + var startTime = DateTime.UtcNow; + BlockChain nullCoin = new BlockChain(genesisDate: new DateTime(2000, 1, 1), difficulty: 2); nullCoin.AddData(new DateTime(2000, 1, 2), "{ sender: VAR, receiver: NAM, amount: 10.00}"); nullCoin.AddData(new DateTime(2000, 1, 3), "{ sender: NAM, receiver: VAR, amount: 5.00}"); nullCoin.AddData(new DateTime(2000, 1, 4), "{ sender: NAM, receiver: VAR, amount: 5.00}"); Console.WriteLine(jsonWriter.Write(nullCoin)); + var endTime = DateTime.UtcNow; + Console.WriteLine($"Duration: {endTime - startTime}"); // Verify Console.WriteLine("BlockChain is Valid? {0}", nullCoin.Verify() ? "True" : "False");