您當前位置>首頁 » 新聞資訊 » 技(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è)簡π™♠單的(de)示例,演示了(le)如(rú)何在C#中實現(xiàn)一(yī)個(gè)簡Ω÷"↔單的(de)區(qū)塊鏈數(shù)據存儲:
```csharp
using System;
using System.Collections.Generic♠₹§;
using System.Security.Cryptography;
public class Block
{
public int Index { get;™ set; }
public DateTime T∑imestamp { get; set; }
public string•∞£ Data { get; set; }
public string PreviousHa₩↕ sh { get; set; }
public string ✘δHash { get; set; }
}
public class Blockchain
{
private List<Block> chain;
public Blockchai→×γn()
{
chain = n≥≈≥γew List<Block>();
// 創建創世•φ區(qū)塊
Addα™GenesisBlock();
}
private void AddGenesisBlock()
{
chain.Add(new☆β' Block
{
≤εσ∑ Index = 0,
&nbs←∞§∑p; Timestamp = DateTimeαλδ.Now,
Data =€≈ "Genesis Block",
Previoφ∏usHash = null,
Ha $sh = CalculateHash(0, DateTime.N'™↓ow, "Genesis Block", null)
});
}
public void AddBlock(strin$₽g data)
{
v∑≤δar previousBlock = chain[chain.C✘ount - 1];
var ne π'☆wBlock = new Block
{
&nbβ→sp; Index = previousB>&lock.Index + 1,
→λαTimestamp = DateTime.Now,
&n•↔↕∞bsp; Data = data,
$≥γ PreviousHash = previo≥¶♠≤usBlock.Hash,
 ¥ ≤; Hash = CalculateHash(previousBlock.∑ΩIndex + 1, DateTime.Now, data, previousλδ♦Block.Hash)
};
chain.Add(newB ↓★lock);
}
private string Calc™↔ulateHash(int index, DateTime ti>÷♥mestamp, string data, string λγpreviousHash)
{
SHA256 sha256 = SHA2✘♣£β56.Create();
byte[] inputBytes =•α System.Text.Encoding.ASCII.GetBytes(index.ToStri♣₩♦ng() + timestamp.ToString() +<±∏← data + previousHash);
byte[] outputBytesα≤♠ = sha256.ComputeHash(inputB∞≠πytes);
return C↑¥onvert.ToBase64String(outputBytes);
}
public bool IsChainV©'$alid()
{
for (int i "☆= 1; i < chain.Count; i++)
{
÷<÷ var currentBlock = chain[i];
&nλδ→ bsp; var previousBlock ≥££= chain[i - 1];
&n ¶•λbsp; if (currentBlock.Hash != &£CalculateHash(currentBlock.Index, currentBlock.T↑ε₩imestamp, currentBlock.Data, currentBlo∑→ck.PreviousHash))
{
 ∑α≠Ω; return♥ π false;
&nb§ sp; }
&nb€φsp; if (currentBlock.PreviousHash×ε♥× != previousBlock.Hash)
{≠¶™↓
&n☆<•>bsp; return fal >se;
}
}
retu∏¥§rn true;
}
}
```
在這(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&g♠★t;`來(lái)存儲區(qū)塊鏈中的(de)所有(yǒu)區(qū)塊。我們還(hái)∑≥¥實現(xiàn)了(le)添加新區(qū)塊的(de)方法`AddB<↔lock`,以及驗證區(qū)塊鏈是(shì)否有(yǒu)效的(de)方法`IsChainVa ≥lid`。
在實際的(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ǐ)。↑ &