forked from djpnewton/acuerdo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Startup.cs
322 lines (285 loc) · 13.3 KB
/
Startup.cs
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Hosting;
using Pomelo.EntityFrameworkCore.MySql;
using Hangfire;
using Hangfire.MySql.Core;
using Hangfire.Dashboard;
using viafront3.Data;
using viafront3.Models;
using viafront3.Services;
namespace viafront3
{
public class GeneralSettings
{
public string SiteName { get; set; }
}
public class MySqlSettings
{
public string Host { get; set; }
public string Database { get; set; }
public string User { get; set; }
public string Password { get; set; }
}
public class AssetSettings
{
public int Decimals { get; set; }
}
public class MarketSettings
{
public string PriceUnit { get; set; }
public string AmountUnit { get; set; }
public int PriceDecimals { get; set; }
public int AmountDecimals { get; set; }
public string PriceInterval { get; set; }
public string AmountInterval { get; set; }
}
public class ExchangeSettings
{
public MySqlSettings MySql { get; set; } = new MySqlSettings();
public string AccessHttpUrl { get; set; } = "http://localhost:8080";
public string AccessWsUrl { get; set; } = "ws://localhost:8090";
public string AccessWsIp { get; set; } = "127.0.0.1";
public string WebsocketUrl { get; set; } = "ws://localhost/ws";
public string KafkaHost { get; set; } = "127.0.0.1:9092";
public Dictionary<string, AssetSettings> Assets { get; set; } = new Dictionary<string, AssetSettings>();
public Dictionary<string, MarketSettings> Markets { get; set; } = new Dictionary<string, MarketSettings>();
public int OrderBookLimit { get; set; } = 99;
public string TakerFeeRate { get; set; } = "0.02";
public string MakerFeeRate { get; set; } = "0.01";
public bool MarketOrderBidAmountMoney { get; set; } = false;
}
public enum LedgerModel
{
Account,
UTXO
}
public class ChainAssetSettings
{
public string NodeUrl { get; set; }
public long FeeUnit { get; set; }
public long FeeMax { get; set; }
public int MinConf { get; set; }
public LedgerModel LedgerModel { get; set; }
}
public class WalletSettings
{
public bool Mainnet { get; set; } = false;
public string ConsolidatedFundsTag { get; set; } = "Consolidate";
public MySqlSettings MySql { get; set; } = new MySqlSettings();
public Dictionary<string, string> DbNames { get; set; } = new Dictionary<string, string>();
public Dictionary<string, ChainAssetSettings> ChainAssetSettings { get; set; } = new Dictionary<string, ChainAssetSettings>();
public Dictionary<string, xchwallet.BankAccount> BankAccounts { get; set; } = new Dictionary<string, xchwallet.BankAccount>();
}
public class EmailSenderSettings
{
public string From { get; set; }
public string SmtpHost { get; set; }
public string SmtpUser { get; set; }
public string SmtpPass { get; set; }
public int SmtpPort { get; set; }
public bool SmtpSsl { get; set; }
public string Signature { get; set; }
public string TemplateFile { get; set; }
}
public class Broker
{
public decimal Fee { get; set; }
public int TimeLimitMinutes { get; set; }
public int TimeLimitGracePeriod { get; set; }
public List<string> SellMarkets { get; set; }
public List<string> BuyMarkets { get; set; }
public Dictionary<string, decimal> MinimumOrderAmount {get; set;}
public string BrokerTag { get; set; }
}
public class ApiSettings
{
public int CreationExpiryMinutes { get; set; }
public Broker Broker { get; set; }
}
public enum WithdrawalPeriod
{
Daily,
Weekly,
Monthly,
}
public class KycLevel
{
public string Name { get; set; }
public string WithdrawalLimit { get; set; }
public override string ToString()
{
return $"Withdrawal limit: {WithdrawalLimit} ({Name})";
}
}
public class KycSettings
{
public List<KycLevel> Levels { get; set; }
public WithdrawalPeriod WithdrawalPeriod { get; set; }
public string WithdrawalAsset { get; set; }
public Dictionary<string, decimal> WithdrawalAssetBaseRates { get; set; } = new Dictionary<string, decimal>();
public bool KycServerEnabled { get; set; }
public string KycServerUrl { get; set; }
public string KycServerApiKey { get; set; }
public string KycServerApiSecret { get; set; }
}
public class TripwireSettings
{
public string AlertEmail { get; set; }
public int TimePeriodInMinutes { get; set; }
public Dictionary<TripwireEventType, int> Maximum { get; set; }
}
public class FiatProcessorSettings
{
public string FiatServerUrl { get; set; }
public string FiatServerApiKey { get; set; }
public string FiatServerSecret { get; set; }
public bool PaymentsEnabled { get; set; }
public string[] PaymentsAssets { get; set; }
public bool PayoutsEnabled { get; set; }
public string[] PayoutsAssets { get; set; }
public string PayoutsReference { get; set; }
}
public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize(DashboardContext context)
{
var httpContext = context.GetHttpContext();
// Allow all authenticated users with the admin role to see the Dashboard.
return httpContext.User.Identity.IsAuthenticated &&
httpContext.User.IsInRole(Utils.AdminRole);
}
}
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add ExchangeSettings so it can be injected in controllers
services.Configure<GeneralSettings>(options => Configuration.GetSection("General").Bind(options));
services.Configure<ExchangeSettings>(options => Configuration.GetSection("Exchange").Bind(options));
services.Configure<WalletSettings>(options => Configuration.GetSection("Wallet").Bind(options));
services.Configure<EmailSenderSettings>(options => Configuration.GetSection("EmailSender").Bind(options));
services.Configure<ApiSettings>(options => Configuration.GetSection("Api").Bind(options));
services.Configure<KycSettings>(options => Configuration.GetSection("Kyc").Bind(options));
services.Configure<TripwireSettings>(options => Configuration.GetSection("Tripwire").Bind(options));
services.Configure<FiatProcessorSettings>(options => Configuration.GetSection("FiatProcessor").Bind(options));
services.AddDbContext<ApplicationDbContext>(options =>
options.UseLazyLoadingProxies()
.UseMySql(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options =>
{
// use our efcore ticket store
options.ExpireTimeSpan = TimeSpan.FromDays(14);
options.SlidingExpiration = true;
options.SessionStore = new EfTicketStore(services.BuildServiceProvider());
// set our session cookie security policy
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Lax;
options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest;
});
services.AddAntiforgery(options =>
{
// set our CSRF cookie security policy
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest;
});
// catch exception which happens if the database does not yet exist because of migrations still in the process of being applied
try
{
// add hangfire service (using out mysql db)
var storage = new MySqlStorage(Configuration.GetConnectionString("DefaultConnection"), new MySqlStorageOptions { TablePrefix = "Hangfire" });
services.AddHangfire(x =>
x.UseStorage(storage));
}
catch
{
Console.WriteLine("Failed to add hangfire! App will fail unless we are just doing design time stuff (migrations etc)");
}
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddSingleton<IWebsocketTokens, WebsocketTokens>();
services.AddSingleton<IWalletProvider, WalletProvider>();
services.AddTransient<IBroker, viafront3.Services.Broker>();
services.AddSingleton<ITripwire, Tripwire>();
services.AddSingleton<IDepositsWithdrawals, DepositsWithdrawals>();
services.AddSingleton<IUserLocks, UserLocks>();
services.AddTransient<IAppVersion, AppVersion>();
services.AddMvc(options =>
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()));
System.ComponentModel.TypeDescriptor.AddAttributes(typeof(DateTime), new System.ComponentModel.TypeConverterAttribute(typeof(NzDateTimeConverter)));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
// enable buffering so our authentication stuff in ApiController can re-read the body after MVC
app.Use((context, next) =>
{
context.Request.EnableBuffering();
return next();
});
// add CSP header
app.Use(async (context, next) =>
{
context.Response.Headers.Add(
"Content-Security-Policy",
"default-src 'self'; script-src 'self'; style-src 'unsafe-inline' 'self'; img-src 'self' data:;");
await next();
});
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
var options = new DashboardOptions
{
Authorization = new[] { new HangfireAuthorizationFilter() }
};
app.UseHangfireDashboard("/hangfire", options);
app.UseHangfireServer();
RecurringJob.AddOrUpdate<IWalletProvider>(
provider => provider.UpdateBlockchainWallets(), "0 */5 * ? * *"); // every 5 minutes
RecurringJob.AddOrUpdate<IBroker>(
broker => broker.ProcessOrders(), "0 */5 * ? * *"); // every 5 minutes
RecurringJob.AddOrUpdate<IDepositsWithdrawals>(
depositsWithdrawals => depositsWithdrawals.ProcessChainDeposits(), "0 */10 * ? * *"); // every 10 minutes
RecurringJob.AddOrUpdate<IDepositsWithdrawals>(
depositsWithdrawals => depositsWithdrawals.ProcessChainWithdrawals(), "0 */10 * ? * *"); // every 10 minutes
RecurringJob.AddOrUpdate<IDepositsWithdrawals>(
depositsWithdrawals => depositsWithdrawals.ProcessFiatWithdrawals(), "0 */10 * ? * *"); // every 10 minutes
var defaultLogLevel = Configuration.GetSection("Logging").GetSection("LogLevel").GetValue<LogLevel>("Default");
loggerFactory.AddFile("logs/viafront-{Date}.txt", defaultLogLevel);
}
}
}