public async Task <bool> LoadBlockchain() { // TODO: When loading chain confirm integrity against peers string[] files = System.IO.Directory.GetFiles(System.IO.Directory.GetCurrentDirectory() + "\\Chain\\"); await Task.Run(() => { foreach (string file in files) { string index = ConvertToChainString(blockHeight); Block b = Serialize.ReadBlock(index); if (blockHeight > 0) { // Testing: Compare hashes // MessageBox.Show(chain.ElementAt(blockHeight - 1).HashBlock() + "\n\n" + b.previousHash); // Check to see if blockchain was tampered with if (b.previousHash != chain.ElementAt(blockHeight - 1).HashBlock()) { //MessageBox.Show("Chain has been modified. Exiting..."); //break; } } chain.Add(b); blockHeight++; network.blockheight = blockHeight; } // Start timer to keep chain in sync timer.Enabled = true; previousBlock = chain.ElementAt(blockHeight - 1); currentBlock = new Block(); currentBlock.NewBlock(blockHeight, previousBlock.HashBlock()); }); return(true); }
private void ReceiveBlock(PacketHeader packetHeader, Connection connection, string blk) { // Deserialize JSON data that is received Block block = Serialize.DeserializeBlock(blk); // Testing MessageBox.Show("Block Received with Hash: \n\n" + block.HashBlock()); // TODO: If it is the same height, disregard. if (block.getIndex() == blockHeight - 1) { //MessageBox.Show("Block received has same height as current block, disregarding..."); } else if (block.getIndex() > blockHeight) { //MessageBox.Show("Block received is more than one block ahead. Finish syncing blockchain..."); // Load method to sync missing blocks // Request block from random peer } else if (block.getIndex() == blockHeight) { if (block.previousHash == previousBlock.HashBlock()) { Serialize.WriteBlock(block); chain.Add(block); blockHeight++; network.blockheight = blockHeight; previousBlock = chain.ElementAt(blockHeight - 1); SendBlock(block); currentBlock = new Block(); currentBlock.NewBlock(blockHeight, previousBlock.HashBlock()); } else { // Block not valid //MessageBox.Show("Hashes do not match, disregarding block..."); } } }
/// <summary> /// Attempts to find the correct hash for the current block. /// </summary> /// <param name="miningWindow">Shows the mining window if set to true.</param> /// <returns>Returns true if this user successfully mined the block.</returns> public async void MineBlock() { // Asks for address to collect mining rewards. Defaults to my address if cancelled. if (miner_id == "") { miner_id = Microsoft.VisualBasic.Interaction.InputBox("Enter the public key that you would like your mining rewards sent to.", "Mining Rewards", "BgIAAACkAABSU0ExAAQAAAEAAQA/KlTgRpoq4gx6RQFiPz+1FAEq5VOUZrfOWJ593nwm7gjsV6x+uxEJRScSLOmBda2PEmVTlFim2Y/Aund29KDXryz16sl6719hR3qZVUkEohAbvPayDJ7r70EAM+oGAU8KiPnyoQqF6bLexEE9yXtA39q94KTPMC4wT7jIhi1E9Q=="); } int count = 0; int count2 = 0; string hashString = "1234567890"; DateTime start = DateTime.Now; DateTime previous = DateTime.Now; mw.ConsoleOutput.Document.Blocks.Clear(); mw.speedWindow.Clear(); await Task.Run(() => { while (hashString.Substring(0, 5) != "00000") { if (mining == false) { break; } byte[] hash; string temp; SHA256Managed hasher = new SHA256Managed(); temp = count.ToString() + previousBlock.index.ToString() + previousBlock.getTimeString() + previousBlock.data.ToString() + previousBlock.previousHash; Byte[] byteArray = Encoding.UTF8.GetBytes(temp); hash = hasher.ComputeHash(byteArray); hashString = string.Empty; foreach (byte x in hash) { hashString += String.Format("{0:x2}", x); } if (count % 1000 == 0) { mw.Dispatcher.Invoke(DispatcherPriority.Render, new Action(() => { mw.ConsoleOutput.AppendText(Environment.NewLine + count.ToString() + " - " + hashString); mw.ConsoleOutput.ScrollToEnd(); })); } DateTime elapsed = DateTime.Now; if (elapsed.Subtract(previous).TotalMilliseconds >= 1000) { mw.Dispatcher.Invoke(DispatcherPriority.Render, new Action(() => { mw.speedWindow.Text = (count2 / 1000).ToString() + " KH/sec"; })); count2 = 0; previous = DateTime.Now; } count++; count2++; } }); if (mining == true) { mw.Dispatcher.Invoke(DispatcherPriority.Render, new Action(() => { mw.ConsoleOutput.AppendText(Environment.NewLine + count.ToString() + " - " + hashString); mw.ConsoleOutput.ScrollToEnd(); })); DateTime finish = DateTime.Now; Double duration = finish.Subtract(start).TotalSeconds; mw.ConsoleOutput.AppendText(Environment.NewLine + "Block time: " + duration.ToString() + " Seconds. Average speed: " + ((count / duration) / 1000).ToString("N2") + " KH/sec."); // Include mining reward in block Transaction reward = new Transaction("miningReward", miner_id, MiningReward(), HashCount(count)); currentBlock.AddTransaction(reward, chain); // Add block to chain Serialize.WriteBlock(currentBlock); chain.Add(currentBlock); blockHeight++; network.blockheight = blockHeight; previousBlock = chain.ElementAt(blockHeight - 1); // Broadcast Block SendBlock(currentBlock); // Create new block currentBlock = new Block(); currentBlock.NewBlock(blockHeight, previousBlock.HashBlock()); // Start mining again MineBlock(); } }