forked from amir-ashy/Blockchain
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEmbedServer.cs
More file actions
84 lines (74 loc) · 2.85 KB
/
EmbedServer.cs
File metadata and controls
84 lines (74 loc) · 2.85 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using EmbedIO;
using EmbedIO.Actions;
using EmbedIO.Routing;
using EmbedIO.WebApi;
using System;
using Newtonsoft.Json;
using System.Linq;
namespace Blockchain
{
public class EmbedServer
{
private WebServer server;
private string url;
public EmbedServer(string port)
{
url = $"http://localhost:{port}/";
server = CreateWebServer(url);
}
public void Stop()
{
server.Dispose();
Console.WriteLine($"http server stopped");
}
public void Start()
{
// Once we've registered our modules and configured them, we call the RunAsync() method.
server.RunAsync();
Console.WriteLine($"http server available at {url}");
}
private WebServer CreateWebServer(string url)
{
var server = new WebServer(o => o
.WithUrlPrefix(url)
.WithMode(HttpListenerMode.EmbedIO))
.WithLocalSessionManager()
.WithWebApi("/api", m => m.WithController<Controller>())
.WithModule(new ActionModule("/", HttpVerbs.Any, ctx => ctx.SendDataAsync(new { Message = "Error" })));
// Listen for state changes.
// server.StateChanged += (s, e) => $"WebServer New State - {e.NewState}".Info();
return server;
}
public sealed class Controller : WebApiController
{
//GET http://localhost:9696/api/blocks
[Route(HttpVerbs.Get, "/blocks")]
public string GetAllBlocks() => JsonConvert.SerializeObject(DependencyManager.BlockMiner.Blockchain);
//GET http://localhost:9696/api/blocks/index/{index?}
[Route(HttpVerbs.Get, "/blocks/index/{index?}")]
public string GetAllBlocks(int index)
{
Model.Block block = null;
if (index < DependencyManager.BlockMiner.Blockchain.Count)
block = DependencyManager.BlockMiner.Blockchain[index];
return JsonConvert.SerializeObject(block);
}
//GET http://localhost:9696/api/blocks/latest
[Route(HttpVerbs.Get, "/blocks/latest")]
public string GetLatestBlocks()
{
var block = DependencyManager.BlockMiner.Blockchain.LastOrDefault();
return JsonConvert.SerializeObject(block);
}
//Post http://localhost:9696/api/add
//Body >> {"From":"amir","To":"bob","Amount":10}
[Route(HttpVerbs.Post, "/add")]
public void AddTransaction()
{
var data = HttpContext.GetRequestDataAsync<Model.Transaction>();
if (data != null && data.Result != null)
DependencyManager.TransactionPool.AddRaw(data.Result);
}
}
}
}