Skip to content

Instantly share code, notes, and snippets.

@antdimot
Last active March 28, 2018 15:26
Show Gist options
  • Save antdimot/cccd55185fd26e89b116762cf4b9bfd4 to your computer and use it in GitHub Desktop.
Save antdimot/cccd55185fd26e89b116762cf4b9bfd4 to your computer and use it in GitHub Desktop.
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() );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment