# C# 200行代码实现区块链

## 2、数据模型

public struct Block { /// /// 区块位置 /// public int Index { get; set; } /// /// 区块生成时间戳 /// public string TimeStamp { get; set; } /// /// 心率数值 /// public int BPM { get; set; } /// /// 区块 SHA-256 散列值 /// public string Hash { get; set; } /// /// 前一个区块 SHA-256 散列值 /// public string PrevHash { get; set; } }

public static class BlockGenerator { public static List_blockChain = new List(); }

## 3、散列与生成区块

/// /// 计算区块 HASH 值 /// ///区块实例 ///计算完成的区块散列值 public static string CalculateHash(Block block) { string calculationStr = \$"{block.Index}{block.TimeStamp}{block.BPM}{block.PrevHash}"; SHA256 sha256Generator = SHA256.Create(); byte[] sha256HashBytes = sha256Generator.ComputeHash(Encoding.UTF8.GetBytes(calculationStr)); StringBuilder sha256StrBuilder = new StringBuilder(); foreach (byte @byte in sha256HashBytes) { sha256StrBuilder.Append(@byte.ToString("x2")); } return sha256StrBuilder.ToString(); }

/// /// 生成新的区块 /// ///旧的区块数据 ///心率 ///新的区块 public static Block GenerateBlock(Block oldBlock, int BPM) { Block newBlock = new Block() { Index = oldBlock.Index + 1, TimeStamp = CalculateCurrentTimeUTC(), BPM = BPM, PrevHash = oldBlock.Hash }; newBlock.Hash = CalculateHash(newBlock); return newBlock; }

/// /// 计算当前时间的 UTC 表示格式 /// ///UTC 时间字符串 public static string CalculateCurrentTimeUTC() { DateTime startTime = new DateTime(1970, 1, 1, 0, 0, 0, 0); DateTime nowTime = DateTime.Now; long unixTime = (long)Math.Round((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero); return unixTime.ToString(); }

## 4、校验区块

• 校验新区块与旧区块的 Index 是否正确递增
• 校验新区块的 Hash 值是否正确
• 校验新区块的 PrevHash 值是否与旧区块的 Hash 值匹配

/// /// 检验区块是否有效 /// ///新生成的区块数据 ///旧的区块数据 ///有效返回 TRUE，无效返回 FALSE public static bool IsBlockValid(Block newBlock, Block oldBlock) { if (oldBlock.Index + 1 != newBlock.Index) return false; if (oldBlock.Hash != newBlock.PrevHash) return false; if (CalculateHash(newBlock) != newBlock.Hash) return false; return true; }

So，我们还需要一个更新最新区块的函数:

/// /// 如果新的区块链比当前区块链更新，则切换当前区块链为最新区块链 /// ///新的区块链 public static void SwitchChain(ListnewBlockChain) { if (newBlockChain.Count > _blockChain.Count) { _blockChain = newBlockChain; } }

## 5、集成到 Web 当中

app.Map("/BlockChain", _ => { _.Run(async context => { if (context.Request.Method == "POST") { // 增加区块链 if (BlockGenerator._blockChain.Count == 0) { Block firstBlock = new Block() { Index = 0, TimeStamp = BlockGenerator.CalculateCurrentTimeUTC(), BPM = 0, Hash = string.Empty, PrevHash = string.Empty }; BlockGenerator._blockChain.Add(firstBlock); await context.Response.WriteAsync(JsonConvert.SerializeObject(firstBlock)); } else { int.TryParse(context.Request.Form["BPM"][0], out int bpm); Block oldBlock = BlockGenerator._blockChain.Last(); Block newBlock = BlockGenerator.GenerateBlock(oldBlock, bpm); if (BlockGenerator.IsBlockValid(newBlock, oldBlock)) { ListnewBlockChain = new List(); foreach (var block in BlockGenerator._blockChain) { newBlockChain.Add(block); } newBlockChain.Add(newBlock); BlockGenerator.SwitchChain(newBlockChain); } await context.Response.WriteAsync(JsonConvert.SerializeObject(newBlock)); } } }); }); app.Map("/BlockChains", _ => { _.Run(async context => { await context.Response.WriteAsync(JsonConvert.SerializeObject(BlockGenerator._blockChain)); }); });

705 篇文章58 人订阅

0 条评论

## 相关文章

### 百度面试总结

http://blog.csdn.net/zhaojinjia/article/details/12649823

32120

547100

38570

35950

24920

15220

24590

29650

29540

22190