antdimot
8/3/2017 - 1:34 PM

Basic Blockchain .Net implementation

Basic Blockchain .Net implementation

using System;
using System.Security.Cryptography;
using System.Text;

namespace Blockchain
{
    public class Block
    {
        private DateTime _timestamp;
        public int Index { get; private set; }
        public string Data { get; private set; }
        public string PreviousHash { get; private set; }

        public Block( int index, string data, string previousHash )
        {
            Index = index;
            Data = data;
            PreviousHash = previousHash;
            _timestamp = DateTime.Now;
        }

        // create the hash value of the block
        public string GetHashValue()
        {
            // block data to hash
            var dataToHash = string.Format( "{0}_{1}_{2}_{3}", Index, _timestamp.ToString(), Data, PreviousHash );

            var hasher = SHA256.Create();

            var hashValue = hasher.ComputeHash( Encoding.UTF8.GetBytes( dataToHash ) );

            return Convert.ToBase64String( hashValue );
        }

        // create the first block of blockchain
        public static Block CreateGenesisBlock() => new Block( 0, "Genesis block", "0" );

        // create next block
        public static Block CreateNextBlock( Block lastBlock, string data ) => 
            new Block( lastBlock.Index + 1, data, lastBlock.GetHashValue() );
    }
}