Example #1
0
        public void GenerateBlock()
        {
            Block newBlock = new Block();
            Hash  blockHash;
            BlockMiningManager miningManager      = new BlockMiningManager();
            DateTime           dateTimeStampBlock = DateTime.UtcNow;
            Hash prevBlockHash = ChainedBlocks.Length - 1 > -1? this.GetBlock(ChainedBlocks.Length - 1).blockHash: null;

            //Add a new block to the chain

            blockHash = miningManager.CalculateHash(prevBlockHash, unconfirmedTransactions, dateTimeStampBlock);                    //Create Hash (use difficulty)

            try
            {
                newBlock.CreateBlock(this, blockHash, dateTimeStampBlock); //Try
                Array.Resize(ref ChainedBlocks, ChainedBlocks.Length + 1);
                ChainedBlocks[ChainedBlocks.Length - 1] = newBlock;

                foreach (var item in unconfirmedTransactions)
                {
                    //Send unconfirmed transactions to block
                    newBlock.AddTransaction(item);
                }

                Console.WriteLine("Added block at height: " + GetHeight() + " DateTime Stamp: " + newBlock.blockDateTimeStamp);

                unconfirmedTransactions.Clear();    //Clear unconfirmed transactions
            }
            catch
            {
                Console.WriteLine("Skipped inserting block due to errors");
                return;
            }
        }
        //This class handles the mining of the block based on the transactions in a block + datetime stamp (utc) + previous hash

        public Hash CalculateHash(Hash _parentHash, IList <BlockTransaction> _unconfirmedTransactions, DateTime _dateTimeStampBlock)
        {
            byte[] Input = BlockMiningManager.GenerateBytes(_parentHash != null? Convert.ToString(_parentHash.GetHashCode()):"", _dateTimeStampBlock.ToString(), Convert.ToString(_unconfirmedTransactions.GetHashCode()));

            //Design decision, vary difficulty by using PBKDF2 or maintain SHA3 256...later to be decided
            Sha3Digest digest = new Sha3Digest(256);

            digest.BlockUpdate(Input, 0, Input.Length);
            byte[] result = new byte[32];
            digest.DoFinal(result, 0);

            return(new Hash(result));
        }