-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockchain.cs
More file actions
56 lines (46 loc) · 1.37 KB
/
Copy pathBlockchain.cs
File metadata and controls
56 lines (46 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Blockchain
{
public class Blockchain
{
public IList<Block> Chain {get; set;}
public Blockchain() {
InitializeChain();
AddGenesisBlock();
}
public void AddBlock(Block newBlock) {
Block latestBlock = GetLatestBlock();
newBlock.Index = latestBlock.Index + 1;
newBlock.PreviousHash = latestBlock.Hash;
newBlock.Hash = newBlock.CalculateHash();
Chain.Add(newBlock);
}
private Block GetLatestBlock() {
return Chain.Last();
}
public bool isValid() {
for(int i = 1; i < Chain.Count; i++) {
Block currentBlock = Chain[i];
Block previousBlock = Chain[i - 1];
if(currentBlock.Hash != currentBlock.CalculateHash()){
return false;
}
if(currentBlock.PreviousHash != previousBlock.Hash)
{
return false;
}
}
return true;
}
private void InitializeChain() {
Chain = new List<Block>();
}
private void AddGenesisBlock()
{
Chain.Add(new Block(0, "0", "Genesis Block"));
}
}
}