C#實現簡單的(de)區塊鏈
發表時(shí)間:2024-1-12
發布人(rén):融晨科技
浏覽次數:33
在(zài)C#中實現區塊鏈的(de)數據存儲可以(yǐ)通過創建一個(gè)自定義的(de)數據結構來(lái)表示區塊鏈中的(de)區塊,然後使用文件或數據庫來(lái)存儲這(zhè)些區塊數據。以(yǐ)下是(shì)一個(gè)簡單的(de)示例,演示了(le/liǎo)如何在(zài)C#中實現一個(gè)簡單的(de)區塊鏈數據存儲:
```csharp
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
public class Block
{
public int Index { get; set; }
public DateTime Timestamp { get; set; }
public string Data { get; set; }
public string PreviousHash { get; set; }
public string Hash { get; set; }
}
public class Blockchain
{
private List<Block> chain;
public Blockchain()
{
chain = new List<Block>();
// 創建創世區塊
AddGenesisBlock();
}
private void AddGenesisBlock()
{
chain.Add(new Block
{
Index = 0,
Timestamp = DateTime.Now,
Data = "Genesis Block",
PreviousHash = null,
Hash = CalculateHash(0, DateTime.Now, "Genesis Block", null)
});
}
public void AddBlock(string data)
{
var previousBlock = chain[chain.Count - 1];
var newBlock = new Block
{
Index = previousBlock.Index + 1,
Timestamp = DateTime.Now,
Data = data,
PreviousHash = previousBlock.Hash,
Hash = CalculateHash(previousBlock.Index + 1, DateTime.Now, data, previousBlock.Hash)
};
chain.Add(newBlock);
}
private string CalculateHash(int index, DateTime timestamp, string data, string previousHash)
{
SHA256 sha256 = SHA256.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(index.ToString() + timestamp.ToString() + data + previousHash);
byte[] outputBytes = sha256.ComputeHash(inputBytes);
return Convert.ToBase64String(outputBytes);
}
public bool IsChainValid()
{
for (int i = 1; i < chain.Count; i++)
{
var currentBlock = chain[i];
var previousBlock = chain[i - 1];
if (currentBlock.Hash != CalculateHash(currentBlock.Index, currentBlock.Timestamp, currentBlock.Data, currentBlock.PreviousHash))
{
return false;
}
if (currentBlock.PreviousHash != previousBlock.Hash)
{
return false;
}
}
return true;
}
}
```
在(zài)這(zhè)個(gè)示例中,我們創建了(le/liǎo)一個(gè)簡單的(de)`Block`類來(lái)表示區塊,以(yǐ)及一個(gè)`Blockchain`類來(lái)表示整個(gè)區塊鏈。在(zài)`Blockchain`類中,我們使用了(le/liǎo)一個(gè)`List<Block>`來(lái)存儲區塊鏈中的(de)所有區塊。我們還實現了(le/liǎo)添加新區塊的(de)方法`AddBlock`,以(yǐ)及驗證區塊鏈是(shì)否有效的(de)方法`IsChainValid`。
在(zài)實際的(de)應用中,你可以(yǐ)将區塊鏈的(de)數據存儲在(zài)文件或者數據庫中。例如,你可以(yǐ)将每個(gè)區塊存儲爲(wéi / wèi)一個(gè)文件,或者将區塊鏈數據存儲在(zài)關系型數據庫或者NoSQL數據庫中。這(zhè)樣就(jiù)可以(yǐ)實現在(zài)C#中對區塊鏈的(de)數據進行存儲和(hé / huò)管理。