-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
285 lines (250 loc) · 10.2 KB
/
Program.cs
File metadata and controls
285 lines (250 loc) · 10.2 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
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
using System.Diagnostics;
using System.IO.Compression;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.FileProviders;
using Photino.Blazor;
using Qubic.Services;
using Qubic.Services.Storage;
using Qubic.Net.Wallet.Components;
namespace Qubic.Net.Wallet;
public class FileDialogService
{
private Photino.NET.PhotinoWindow? _window;
public void SetWindow(Photino.NET.PhotinoWindow window) => _window = window;
public bool IsAvailable => _window != null;
public Task<string?> ShowSaveFileAsync(string title, string defaultPath,
string defaultExtension = ".dat",
params (string Name, string[] Extensions)[] filters)
{
if (_window == null) return Task.FromResult<string?>(null);
var safePath = NormalizePath(defaultPath);
return Task.Run(() =>
{
var path = _window.ShowSaveFile(title, safePath, filters);
if (path != null && !string.IsNullOrEmpty(defaultExtension)
&& !Path.HasExtension(path))
path += defaultExtension;
return path;
});
}
public Task<string?> ShowOpenFileAsync(string title, string defaultPath,
params (string Name, string[] Extensions)[] filters)
{
if (_window == null) return Task.FromResult<string?>(null);
var safePath = NormalizePath(defaultPath);
return Task.Run(() =>
{
var result = _window.ShowOpenFile(title, safePath, false, filters);
return result?.FirstOrDefault();
});
}
/// <summary>
/// Photino's native dialog expects defaultPath to be an existing directory.
/// If a full file path is given, extract the directory portion.
/// </summary>
private static string NormalizePath(string path)
{
if (string.IsNullOrWhiteSpace(path)) return "";
// If it looks like a file path (has extension), use the directory
if (Path.HasExtension(path))
{
var dir = Path.GetDirectoryName(path);
return dir ?? "";
}
return path;
}
}
class Program
{
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool AllocConsole();
[STAThread]
static void Main(string[] args)
{
if (args.Contains("--server"))
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
AllocConsole();
RunServer(args);
}
else
{
try
{
RunDesktop(args);
}
catch (Exception ex) when (ex is DllNotFoundException || ex.InnerException is DllNotFoundException)
{
Console.Error.WriteLine("Desktop mode failed: native library not available.");
Console.Error.WriteLine(ex.InnerException?.Message ?? ex.Message);
Console.Error.WriteLine();
Console.Error.WriteLine("Falling back to server mode (--server)...");
Console.Error.WriteLine();
RunServer(args);
}
}
}
static void RegisterServices(IServiceCollection services)
{
SQLitePCL.Batteries_V2.Init();
services.AddSingleton(new QubicSettingsService("QubicWallet"));
services.AddSingleton<QubicBackendService>();
services.AddSingleton<SeedSessionService>();
services.AddSingleton<VaultService>();
services.AddSingleton<TickMonitorService>();
services.AddSingleton<TickDriftService>();
services.AddSingleton<WalletDatabase>();
services.AddSingleton<WalletSyncService>();
services.AddSingleton<WalletStorageService>();
services.AddSingleton<TransactionTrackerService>();
services.AddSingleton<AssetRegistryService>();
services.AddSingleton<PeerAutoDiscoverService>();
services.AddSingleton<QubicStaticService>();
services.AddSingleton<LabelService>();
services.AddSingleton<AutoLockService>();
services.AddSingleton<BalanceService>();
services.AddSingleton(new FileDialogService());
services.AddLocalization();
}
static void RunDesktop(string[] args)
{
var wwwrootPath = GetWwwrootPath();
var fileProvider = new PhysicalFileProvider(wwwrootPath);
var appBuilder = PhotinoBlazorAppBuilder.CreateDefault(fileProvider, args);
RegisterServices(appBuilder.Services);
appBuilder.RootComponents.Add<Routes>("app");
var app = appBuilder.Build();
app.Services.GetRequiredService<FileDialogService>().SetWindow(app.MainWindow);
var iconPath = GetIconPath();
app.MainWindow
.SetTitle("Qubic.Net Wallet")
.SetSize(1200, 800);
if (iconPath != null)
app.MainWindow.SetIconFile(iconPath);
AppDomain.CurrentDomain.UnhandledException += (sender, error) =>
{
app.MainWindow.ShowMessage("Fatal exception", error.ExceptionObject.ToString());
};
app.Run();
}
const string SessionCookieName = ".QubicWallet.Session";
static void RunServer(string[] args)
{
var wwwrootPath = GetWwwrootPath();
var sessionToken = Convert.ToHexString(RandomNumberGenerator.GetBytes(16)).ToLowerInvariant();
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorComponents().AddInteractiveServerComponents();
RegisterServices(builder.Services);
builder.WebHost.UseUrls("http://127.0.0.1:0");
builder.Environment.WebRootPath = wwwrootPath;
var app = builder.Build();
// Session token middleware: validates every request before anything else.
// First request arrives with ?token=xxx — we set an HttpOnly cookie and redirect
// to strip the token from the URL. All subsequent requests are validated via cookie.
app.Use(async (context, next) =>
{
// Check for token in query string (initial browser open)
if (context.Request.Query.TryGetValue("token", out var tokenValue)
&& tokenValue.ToString() == sessionToken)
{
context.Response.Cookies.Append(SessionCookieName, sessionToken, new CookieOptions
{
HttpOnly = true,
SameSite = SameSiteMode.Strict,
Secure = false, // localhost HTTP
Path = "/",
IsEssential = true
});
// Redirect to root to strip token from URL / browser history
context.Response.Redirect("/");
return;
}
// Validate cookie on all requests
if (!context.Request.Cookies.TryGetValue(SessionCookieName, out var cookie)
|| cookie != sessionToken)
{
context.Response.StatusCode = 403;
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync("Access denied. Open the app from the URL shown in the console.");
return;
}
await next();
});
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(wwwrootPath)
});
app.UseAntiforgery();
app.MapRazorComponents<App>().AddInteractiveServerRenderMode();
app.Lifetime.ApplicationStarted.Register(() =>
{
var address = app.Urls.FirstOrDefault() ?? "http://127.0.0.1:5060";
var authUrl = $"{address}?token={sessionToken}";
Console.WriteLine($"Qubic.Net Wallet running at {address}");
Console.WriteLine();
#if DEBUG
Console.WriteLine($"Open in browser: {authUrl}");
#endif
try
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
Process.Start(new ProcessStartInfo(authUrl) { UseShellExecute = true });
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
Process.Start("open", authUrl);
else
Process.Start("xdg-open", authUrl);
}
catch { /* Browser auto-open is best-effort */ }
});
app.Run();
}
static string? GetIconPath()
{
var basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "icon.ico");
if (File.Exists(basePath))
return basePath;
using var stream = typeof(Program).Assembly.GetManifestResourceStream("icon.ico");
if (stream == null)
return null;
var appData = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"QubicWallet");
Directory.CreateDirectory(appData);
var iconPath = Path.Combine(appData, "icon.ico");
using var fs = File.Create(iconPath);
stream.CopyTo(fs);
return iconPath;
}
static string GetWwwrootPath()
{
var stream = typeof(Program).Assembly.GetManifestResourceStream("wwwroot.zip");
if (stream == null)
{
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot");
}
var appData = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"QubicWallet");
var wwwrootDir = Path.Combine(appData, "wwwroot");
var versionFile = Path.Combine(wwwrootDir, ".version");
var currentVersion = typeof(Program).Assembly.ManifestModule.ModuleVersionId.ToString();
if (Directory.Exists(wwwrootDir) && File.Exists(versionFile)
&& File.ReadAllText(versionFile).Trim() == currentVersion)
{
stream.Dispose();
return wwwrootDir;
}
using (stream)
using (var archive = new ZipArchive(stream, ZipArchiveMode.Read))
{
if (Directory.Exists(wwwrootDir))
Directory.Delete(wwwrootDir, true);
Directory.CreateDirectory(wwwrootDir);
archive.ExtractToDirectory(wwwrootDir);
}
File.WriteAllText(versionFile, currentVersion);
return wwwrootDir;
}
}