-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockManager.cs
More file actions
59 lines (51 loc) · 1.74 KB
/
BlockManager.cs
File metadata and controls
59 lines (51 loc) · 1.74 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
57
58
59
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blockchain
{
public static class BlockManager
{
private const string PATH = @"Blocks\";
public static Dictionary<string, Block> Blocks = new Dictionary<string, Block>();
private static readonly Random random = new Random();
private const string CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
public static void CreateBlock(string data)
{
Block block = new Block()
{
data = data,
timestamp = DateTime.Now,
index = Blocks.Count + 1
};
block.prev_hash = Blocks.Count == 0 ? "" : Blocks.Values.Last().hash;
block.hash = block.GetHash();
Blocks.Add(block.hash, block);
}
public static void Load()
{
Blocks.Clear();
foreach (string block_path in Directory.GetFiles(PATH))
{
string json = File.ReadAllText(block_path);
Block block = JsonConvert.DeserializeObject<Block>(json);
Blocks.Add(block.hash, block);
}
}
public static void Save()
{
foreach (Block block in Blocks.Values)
{
string json = JsonConvert.SerializeObject(block, Formatting.Indented);
File.WriteAllText(PATH + $"Block_{block.index}.json", json);
}
}
public static string RandomString(int length)
{
return new string(Enumerable.Repeat(CHARS, length).Select(s => s[random.Next(s.Length)]).ToArray());
}
}
}