Skip to content

Instantly share code, notes, and snippets.

View amir-ashy's full-sized avatar

amirreza sharifi amir-ashy

View GitHub Profile
using System;
using System.Collections.Generic;
namespace Blockchain.Model
{
public class Block
{
public long Index { get; set; }
public DateTime TimeStamp { get; set; }
public string Hash { get; set; }
namespace Blockchain.Model
{
public class Transaction
{
public Transaction() { }
public Transaction(string from, string to, int amount)
{
this.From = from;
this.To = to;
using Blockchain.Model;
using System.Collections.Generic;
using System.Linq;
namespace Blockchain
{
public class TransactionPool
{
private List<Transaction> rawTransactionList;
public List<Block> Blockchain { get; private set; }
public static string CalculateHash(string rawData)
{
// Create a SHA256
using (SHA256 sha256Hash = SHA256.Create())
{
// ComputeHash - returns byte array
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
// Convert byte array to a string
StringBuilder builder = new StringBuilder();
private string FindMerkleRootHash(IList<Transaction> transactionList)
{
var transactionStrList = transactionList.Select(tran => CalculateHash(CalculateHash(tran.From + tran.To + tran.Amount))).ToList();
return BuildMerkleRootHash(transactionStrList);
}
private string BuildMerkleRootHash(IList<string> merkelLeaves)
{
if (merkelLeaves == null || !merkelLeaves.Any())
return string.Empty;
private void GenerateBlock()
{
var lastBlock = Blockchain.LastOrDefault();
var block = new Block()
{
TimeStamp = DateTime.Now,
Nounce = 0,
TransactionList = TransactionPool.TakeAll(),
Index = (lastBlock?.Index + 1 ?? 0),
PrevHash = lastBlock?.Hash ?? string.Empty
public void Start()
{
cancellationToken = new CancellationTokenSource();
Task.Run(() => DoGenerateBlock(), cancellationToken.Token);
Console.WriteLine("Mining has started");
}
public void Stop()
{
cancellationToken.Cancel();
Console.WriteLine("Mining has stopped");
namespace Blockchain
{
public class EmbedServer
{
private WebServer server;
private string url;
public EmbedServer(string port)
{
url = $"http://localhost:{port}/";
server = CreateWebServer(url);