您當前位置>首頁 » 新聞資訊 » 技(jì)術(shù)分(fēn)享 >
C#實現(xiàn)簡單的(de)區(qū)塊鏈
發表時(shí)間(jiān):2024-1-12
發布人(rén):葵宇科(kē)技(jì)
浏覽次數(shù):53
在C#中實現(xiàn)區(qū)塊鏈的(de)數(shù)據存儲可(k×¶ě)以通(tōng)過創建一(yī)個(gè)自(zì±σ¥≈)定義的(de)數(shù)據結構來(lái)表示區(qū)塊鏈中的(de)區(qū)塊,然後α®使用(yòng)文(wén)件(jiàn)或數(shù)據庫來(l ≈≤↔ái)存儲這(zhè)些(xiē)區(qū)塊數(sh♠↓≠ù)據。以下(xià)是(shì)一(yī)個(gè)簡單的(d₹™₽>e)示例,演示了(le)如(rú)何在C#中實現(xiàn)一(£♦yī)個(gè)簡單的(de)區(qū)塊鏈數(shù↔♦☆)據存儲:
```csharp
using System;
using System.Collections.Generic;
using System.Security.Cryp ×λ★tography;
public class Block
{
public int Ind↓εex { get; set; }
public DateTime Timestamp { getα♠; set; }
public string Data { get; €® ×set; }
public string PreviousHaλ™÷sh { get; set; }
public string Hash { get; se₽→♠t; }
}
public class Blockchain
{
private List<Block> cΩφ✘ hain;
public Blockchain∑€ ≥()
{
chain ∏ = new List<Block>();
// 創建創世區(qū)塊♠€
AddGen™£esisBlock();
}
private void AddGenesis ¥←↑Block()
{
chain.Add(new Block
{
&nb₹ ✔sp; Index = 0,
™¥Timestamp = DateTime.Now,
∞ Data = "Genesis Block",✔☆α
Prev"™γiousHash = null,
Hash γγλ= CalculateHash(0, DateTime.Now®♥∞®, "Genesis Block", null)
});
}
public void AddBloc>₹k(string data)
{
var previousBlock'₽∞ = chain[chain.Count - 1];
  ≠; var newBlock = new Blockσ₹
✔¥§ {
₩ Index = previousBlock.Index + ★'1,
&n'>↔✘bsp; Timestamp = DateTim→'α$e.Now,
&←'nbsp; Data = data,
≤€σ PreviousHash = previ<€♥ousBlock.Hash,
Hash¶™Ω = CalculateHash(previousBlock.Index + 1 β•®, DateTime.Now, data, previousBlock.Hash)
};
>φ♠' chain.Add(newBlock);
}
private string CalculateHash(inφΩ™t index, DateTime timestamp, string data, stri"Ω★♦ng previousHash)
{
SHA256≈∏ sha256 = SHA256.Create();
byte[] inputBytes ☆←←= System.Text.Encoding.ASCII.GetBytes(in₹ε'dex.ToString() + timestamp.ToStr™→ing() + data + previousHash);
byte[] outputByt&≈es = sha256.ComputeHash(inputBytes);
return Con$ ☆↑vert.ToBase64String(outputBytes);
}
public bool IsChainV∑σ∑alid()
{
for (int i = 1; £i < chain.Count; i++)
{
&nbs↔α♠←p; var currentBlock = chain[i];
∏& var previousBlock = chain[i - 1];
&nbs₩↕♥p; if (currentBlock.Hash != CalculateHash(curre₽±β↕ntBlock.Index, currentBlock.Timestamp←↓♦, currentBlock.Data, curren™±™₹tBlock.PreviousHash))
&nb↕ sp; {
&nbε∑sp; return false;
&nb₹∞sp; }
 φ>♦ ; if (currentBlock.PreviousHash != ¶₹¶φpreviousBlock.Hash)
&nb¶'sp; {
&n↔ bsp; return false;
 ™∏€™; }
}
return trφ™≥≈ue;
}
}
```
在這(zhè)個(gè)示例中,我們創建了(le)一(yī♠↕¥<)個(gè)簡單的(de)`Block`類來(lái)表示區(qū≤')塊,以及一(yī)個(gè)`Blockchain₩®≥©`類來(lái)表示整個(gè)區(qū)塊鏈。在`Blockchain`類中,我們使用(y'✔λòng)了(le)一(yī)個(gè)`List<Block>`來(lái)¥ ↔©存儲區(qū)塊鏈中的(de)所有(yǒu)區(qū)塊。我們還(hái)實現(€≠♥xiàn)了(le)添加新區(qū)塊的(de)方法`AddBlockγ¥<±`,以及驗證區(qū)塊鏈是(shì)否有(yǒu)效的(deπ•)方法`IsChainValid`。
在實際的(de)應用(yòng)中,你(nǐ)可(kě)以将區(qū)塊鏈×<&₩的(de)數(shù)據存儲在文(wén)件(jiàn)或者數(shù)據庫中。例如 ₹(rú),你(nǐ)可(kě)以将每個(gè)區(qū)塊存儲為(wèi)一(yī)個∏÷(gè)文(wén)件(jiàn),或者将區(qū)塊鏈數(shù)據存儲在關系型數α↑•∏(shù)據庫或者NoSQL數(shù)據庫中。這(β₹ zhè)樣就(jiù)可(kě)以實現(xiàn)在C₽ε"#中對(duì)區(qū)塊鏈的(de)數(shù)據進行(xíng)存儲和(h✔$ é)管理(lǐ)。