forked from zkSNACKs/WalletWasabi
/
Global.cs
715 lines (610 loc) · 22.1 KB
/
Global.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
using Avalonia;
using Avalonia.Threading;
using NBitcoin;
using NBitcoin.Protocol;
using NBitcoin.Protocol.Behaviors;
using NBitcoin.Protocol.Connectors;
using Nito.AsyncEx;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Crypto;
using WalletWasabi.Gui.Dialogs;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Helpers;
using WalletWasabi.Hwi;
using WalletWasabi.KeyManagement;
using WalletWasabi.Logging;
using WalletWasabi.Models;
using WalletWasabi.Services;
using WalletWasabi.Stores;
using WalletWasabi.TorSocks5;
namespace WalletWasabi.Gui
{
public class Global
{
public const string GlobalResourceKey = "Wasabi.Ui.Global";
public const string ConfigResourceKey = "Wasabi.Ui.Config";
public const string UiConfigResourceKey = "Wasabi.Ui.UiConfig";
public const string ThemeBackgroundBrushResourceKey = "ThemeBackgroundBrush";
public const string ApplicationAccentForegroundBrushResourceKey = "ApplicationAccentForegroundBrush";
public string DataDir { get; }
public string TorLogsFile { get; }
public string WalletsDir { get; }
public string WalletBackupsDir { get; }
public BitcoinStore BitcoinStore { get; private set; }
public Config Config { get; private set; }
public string AddressManagerFilePath { get; private set; }
public AddressManager AddressManager { get; private set; }
public MempoolService MempoolService { get; private set; }
public NodesGroup Nodes { get; private set; }
public WasabiSynchronizer Synchronizer { get; private set; }
public CcjClient ChaumianClient { get; private set; }
public WalletService WalletService { get; private set; }
public Node RegTestMempoolServingNode { get; private set; }
public UpdateChecker UpdateChecker { get; private set; }
public TorProcessManager TorManager { get; private set; }
public bool KillRequested { get; private set; } = false;
public UiConfig UiConfig { get; private set; }
public Network Network => Config.Network;
public Global()
{
DataDir = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Client"));
TorLogsFile = Path.Combine(DataDir, "TorLogs.txt");
WalletsDir = Path.Combine(DataDir, "Wallets");
WalletBackupsDir = Path.Combine(DataDir, "WalletBackups");
Directory.CreateDirectory(DataDir);
Directory.CreateDirectory(WalletsDir);
Directory.CreateDirectory(WalletBackupsDir);
}
public void InitializeUiConfig(UiConfig uiConfig)
{
UiConfig = Guard.NotNull(nameof(uiConfig), uiConfig);
}
private int _isDesperateDequeuing = 0;
public async Task TryDesperateDequeueAllCoinsAsync()
{
// If already desperate dequeuing then return.
// If not desperate dequeuing then make sure we're doing that.
if (Interlocked.CompareExchange(ref _isDesperateDequeuing, 1, 0) == 1)
{
return;
}
try
{
await DesperateDequeueAllCoinsAsync();
}
catch (NotSupportedException ex)
{
Logger.LogWarning(ex.Message, nameof(Global));
}
catch (Exception ex)
{
Logger.LogWarning(ex, nameof(Global));
}
finally
{
Interlocked.Exchange(ref _isDesperateDequeuing, 0);
}
}
public async Task DesperateDequeueAllCoinsAsync()
{
if (WalletService is null || ChaumianClient is null)
{
return;
}
SmartCoin[] enqueuedCoins = WalletService.Coins.Where(x => x.CoinJoinInProgress).ToArray();
if (enqueuedCoins.Any())
{
Logger.LogWarning("Unregistering coins in CoinJoin process.", nameof(Global));
await ChaumianClient.DequeueCoinsFromMixAsync(enqueuedCoins, "Process was signaled to kill.");
}
}
private bool Initialized { get; set; } = false;
public async Task InitializeNoWalletAsync()
{
WalletService = null;
ChaumianClient = null;
AddressManager = null;
TorManager = null;
#region ConfigInitialization
Config = new Config(Path.Combine(DataDir, "Config.json"));
await Config.LoadOrCreateDefaultFileAsync();
Logger.LogInfo<Config>($"{nameof(Config)} is successfully initialized.");
#endregion ConfigInitialization
BitcoinStore = new BitcoinStore();
var bstoreInitTask = BitcoinStore.InitializeAsync(Path.Combine(DataDir, $"{nameof(BitcoinStore)}"), Network);
var hwiInitTask = HwiProcessManager.InitializeAsync(DataDir, Network);
var addressManagerFolderPath = Path.Combine(DataDir, $"{nameof(AddressManager)}");
AddressManagerFilePath = Path.Combine(addressManagerFolderPath, $"{nameof(AddressManager)}{Network}.dat");
var addrManTask = InitializeAddressManagerBehaviorAsync();
var blocksFolderPath = Path.Combine(DataDir, $"Blocks{Network}");
var connectionParameters = new NodeConnectionParameters { UserAgent = "/Satoshi:0.18.0/" };
if (Config.UseTor)
{
Synchronizer = new WasabiSynchronizer(Network, BitcoinStore, () => Config.GetCurrentBackendUri(), Config.TorSocks5EndPoint);
}
else
{
Synchronizer = new WasabiSynchronizer(Network, BitcoinStore, Config.GetFallbackBackendUri(), null);
}
UpdateChecker = new UpdateChecker(Synchronizer.WasabiClient);
#region ProcessKillSubscription
AppDomain.CurrentDomain.ProcessExit += async (s, e) => await TryDesperateDequeueAllCoinsAsync();
Console.CancelKeyPress += async (s, e) =>
{
e.Cancel = true;
Logger.LogWarning("Process was signaled for killing.", nameof(Global));
KillRequested = true;
await TryDesperateDequeueAllCoinsAsync();
Dispatcher.UIThread.PostLogException(() =>
{
Application.Current?.MainWindow?.Close();
});
await DisposeAsync();
Logger.LogInfo($"Wasabi stopped gracefully.", Logger.InstanceGuid.ToString());
};
#endregion ProcessKillSubscription
#region TorProcessInitialization
if (Config.UseTor)
{
TorManager = new TorProcessManager(Config.TorSocks5EndPoint, TorLogsFile);
}
else
{
TorManager = TorProcessManager.Mock();
}
TorManager.Start(false, DataDir);
var fallbackRequestTestUri = new Uri(Config.GetFallbackBackendUri(), "/api/software/versions");
TorManager.StartMonitor(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(7), DataDir, fallbackRequestTestUri);
Logger.LogInfo<TorProcessManager>($"{nameof(TorProcessManager)} is initialized.");
#endregion TorProcessInitialization
#region MempoolInitialization
MempoolService = new MempoolService();
connectionParameters.TemplateBehaviors.Add(new MempoolBehavior(MempoolService));
#endregion MempoolInitialization
#region HwiProcessInitialization
try
{
await hwiInitTask;
}
catch (Exception ex)
{
Logger.LogError(ex, nameof(Global));
}
#endregion HwiProcessInitialization
#region BitcoinStoreInitialization
await bstoreInitTask;
#endregion BitcoinStoreInitialization
#region AddressManagerInitialization
AddressManagerBehavior addressManagerBehavior = await addrManTask;
connectionParameters.TemplateBehaviors.Add(addressManagerBehavior);
#endregion AddressManagerInitialization
#region P2PInitialization
if (Network == Network.RegTest)
{
Nodes = new NodesGroup(Network, requirements: Constants.NodeRequirements);
try
{
Node node = await Node.ConnectAsync(Network.RegTest, new IPEndPoint(IPAddress.Loopback, 18444));
Nodes.ConnectedNodes.Add(node);
RegTestMempoolServingNode = await Node.ConnectAsync(Network.RegTest, new IPEndPoint(IPAddress.Loopback, 18444));
RegTestMempoolServingNode.Behaviors.Add(new MempoolBehavior(MempoolService));
}
catch (SocketException ex)
{
Logger.LogError(ex, nameof(Global));
}
}
else
{
if (Config.UseTor is true)
{
// onlyForOnionHosts: false - Connect to clearnet IPs through Tor, too.
connectionParameters.TemplateBehaviors.Add(new SocksSettingsBehavior(Config.TorSocks5EndPoint, onlyForOnionHosts: false, networkCredential: null, streamIsolation: true));
// allowOnlyTorEndpoints: true - Connect only to onions and do not connect to clearnet IPs at all.
// This of course makes the first setting unnecessary, but it's better if that's around, in case someone wants to tinker here.
connectionParameters.EndpointConnector = new DefaultEndpointConnector(allowOnlyTorEndpoints: Network == Network.Main);
await AddKnownBitcoinFullNodeAsHiddenServiceAsync(AddressManager);
}
Nodes = new NodesGroup(Network, connectionParameters, requirements: Constants.NodeRequirements);
RegTestMempoolServingNode = null;
}
Nodes.Connect();
Logger.LogInfo("Start connecting to nodes...");
if (RegTestMempoolServingNode != null)
{
RegTestMempoolServingNode.VersionHandshake();
Logger.LogInfo("Start connecting to mempool serving regtest node...");
}
#endregion P2PInitialization
#region SynchronizerInitialization
var requestInterval = TimeSpan.FromSeconds(30);
if (Network == Network.RegTest)
{
requestInterval = TimeSpan.FromSeconds(5);
}
int maxFiltSyncCount = Network == Network.Main ? 1000 : 10000; // On testnet, filters are empty, so it's faster to query them together
Synchronizer.Start(requestInterval, TimeSpan.FromMinutes(5), maxFiltSyncCount);
Logger.LogInfo("Start synchronizing filters...");
#endregion SynchronizerInitialization
Initialized = true;
}
private async Task<AddressManagerBehavior> InitializeAddressManagerBehaviorAsync()
{
var needsToDiscoverPeers = true;
if (Network == Network.RegTest)
{
AddressManager = new AddressManager();
Logger.LogInfo<AddressManager>($"Fake {nameof(AddressManager)} is initialized on the {Network.RegTest}.");
}
else
{
try
{
AddressManager = await NBitcoinHelpers.LoadAddressManagerFromPeerFileAsync(AddressManagerFilePath);
// Most of the times we do not need to discover new peers. Instead, we can connect to
// some of those that we already discovered in the past. In this case we assume that
// discovering new peers could be necessary if our address manager has less
// than 500 addresses. 500 addresses could be okay because previously we tried with
// 200 and only one user reported he/she was not able to connect (there could be many others,
// of course).
// On the other side, increasing this number forces users that do not need to discover more peers
// to spend resources (CPU/bandwith) to discover new peers.
needsToDiscoverPeers = Config.UseTor is true || AddressManager.Count < 500;
Logger.LogInfo<AddressManager>($"Loaded {nameof(AddressManager)} from `{AddressManagerFilePath}`.");
}
catch (DirectoryNotFoundException ex)
{
Logger.LogInfo<AddressManager>($"{nameof(AddressManager)} did not exist at `{AddressManagerFilePath}`. Initializing new one.");
Logger.LogTrace<AddressManager>(ex);
AddressManager = new AddressManager();
}
catch (FileNotFoundException ex)
{
Logger.LogInfo<AddressManager>($"{nameof(AddressManager)} did not exist at `{AddressManagerFilePath}`. Initializing new one.");
Logger.LogTrace<AddressManager>(ex);
AddressManager = new AddressManager();
}
catch (OverflowException ex)
{
// https://github.com/zkSNACKs/WalletWasabi/issues/712
Logger.LogInfo<AddressManager>($"{nameof(AddressManager)} has thrown `{nameof(OverflowException)}`. Attempting to autocorrect.");
File.Delete(AddressManagerFilePath);
Logger.LogTrace<AddressManager>(ex);
AddressManager = new AddressManager();
Logger.LogInfo<AddressManager>($"{nameof(AddressManager)} autocorrection is successful.");
}
catch (FormatException ex)
{
// https://github.com/zkSNACKs/WalletWasabi/issues/880
Logger.LogInfo<AddressManager>($"{nameof(AddressManager)} has thrown `{nameof(FormatException)}`. Attempting to autocorrect.");
File.Delete(AddressManagerFilePath);
Logger.LogTrace<AddressManager>(ex);
AddressManager = new AddressManager();
Logger.LogInfo<AddressManager>($"{nameof(AddressManager)} autocorrection is successful.");
}
}
var addressManagerBehavior = new AddressManagerBehavior(AddressManager)
{
Mode = needsToDiscoverPeers ? AddressManagerBehaviorMode.Discover : AddressManagerBehaviorMode.None
};
return addressManagerBehavior;
}
private async Task AddKnownBitcoinFullNodeAsHiddenServiceAsync(AddressManager addressManager)
{
if (Network == Network.RegTest)
{
return;
}
// curl -s https://bitnodes.21.co/api/v1/snapshots/latest/ | egrep -o '[a-z0-9]{16}\.onion:?[0-9]*' | sort -ru
// Then filtered to include only /Satoshi:0.17.x
var fullBaseDirectory = Path.GetFullPath(AppContext.BaseDirectory);
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
if (!fullBaseDirectory.StartsWith('/'))
{
fullBaseDirectory.Insert(0, "/");
}
}
var onions = await File.ReadAllLinesAsync(Path.Combine(fullBaseDirectory, "OnionSeeds", $"{Network}OnionSeeds.txt"));
onions.Shuffle();
foreach (var onion in onions.Take(60))
{
if (Utils.TryParseEndpoint(onion, Network.DefaultPort, out var endpoint))
{
await addressManager.AddAsync(endpoint);
}
}
}
private CancellationTokenSource _cancelWalletServiceInitialization = null;
public async Task InitializeWalletServiceAsync(KeyManager keyManager)
{
using (_cancelWalletServiceInitialization = new CancellationTokenSource())
{
var token = _cancelWalletServiceInitialization.Token;
while (!Initialized)
{
await Task.Delay(100, token);
}
if (Config.UseTor)
{
ChaumianClient = new CcjClient(Synchronizer, Network, keyManager, () => Config.GetCurrentBackendUri(), Config.TorSocks5EndPoint);
}
else
{
ChaumianClient = new CcjClient(Synchronizer, Network, keyManager, Config.GetFallbackBackendUri(), null);
}
try
{
keyManager.CorrectBlockHeights(BitcoinStore.HashChain); // Block heights are wrong sometimes. It's a hack. We have to retroactively fix existing wallets, but also we have to figure out where we ruin the block heights.
}
catch (Exception ex) // Whatever this is not critical, but let's log it.
{
Logger.LogWarning(ex, nameof(Global));
}
WalletService = new WalletService(BitcoinStore, keyManager, Synchronizer, ChaumianClient, MempoolService, Nodes, DataDir, Config.ServiceConfiguration);
ChaumianClient.Start();
Logger.LogInfo("Start Chaumian CoinJoin service...");
Logger.LogInfo($"Starting {nameof(WalletService)}...");
await WalletService.InitializeAsync(token);
Logger.LogInfo($"{nameof(WalletService)} started.");
token.ThrowIfCancellationRequested();
WalletService.Coins.CollectionChanged += Coins_CollectionChanged;
}
_cancelWalletServiceInitialization = null; // Must make it null explicitly, because dispose won't make it null.
}
public string GetWalletFullPath(string walletName)
{
walletName = walletName.TrimEnd(".json", StringComparison.OrdinalIgnoreCase);
return Path.Combine(WalletsDir, walletName + ".json");
}
public string GetWalletBackupFullPath(string walletName)
{
walletName = walletName.TrimEnd(".json", StringComparison.OrdinalIgnoreCase);
return Path.Combine(WalletBackupsDir, walletName + ".json");
}
public KeyManager LoadKeyManager(string walletFullPath, string walletBackupFullPath)
{
try
{
return LoadKeyManager(walletFullPath);
}
catch (Exception ex)
{
if (!File.Exists(walletBackupFullPath))
{
throw;
}
Logger.LogWarning($"Wallet got corrupted.\n" +
$"Wallet Filepath: {walletFullPath}\n" +
$"Trying to recover it from backup.\n" +
$"Backup path: {walletBackupFullPath}\n" +
$"Exception: {ex}");
if (File.Exists(walletFullPath))
{
string corruptedWalletBackupPath = Path.Combine(WalletBackupsDir, $"{Path.GetFileName(walletFullPath)}_CorruptedBackup");
if (File.Exists(corruptedWalletBackupPath))
{
File.Delete(corruptedWalletBackupPath);
Logger.LogInfo($"Deleted previous corrupted wallet file backup from `{corruptedWalletBackupPath}`.");
}
File.Move(walletFullPath, corruptedWalletBackupPath);
Logger.LogInfo($"Backed up corrupted wallet file to `{corruptedWalletBackupPath}`.");
}
File.Copy(walletBackupFullPath, walletFullPath);
return LoadKeyManager(walletFullPath);
}
}
public KeyManager LoadKeyManager(string walletFullPath)
{
KeyManager keyManager;
// Set the LastAccessTime.
new FileInfo(walletFullPath)
{
LastAccessTime = DateTime.Now
};
keyManager = KeyManager.FromFile(walletFullPath);
Logger.LogInfo($"Wallet loaded: {Path.GetFileNameWithoutExtension(keyManager.FilePath)}.");
return keyManager;
}
private void Coins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
try
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || UiConfig?.LurkingWifeMode is true)
{
return;
}
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (SmartCoin coin in e.NewItems)
{
//if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && RuntimeInformation.OSDescription.StartsWith("Microsoft Windows 10"))
//{
// // It's harder than you'd think. Maybe the best would be to wait for .NET Core 3 for WPF things on Windows?
//}
// else
if (coin.HdPubKey.IsInternal)
{
continue;
}
string amountString = coin.Amount.ToString(false, true);
using (var process = Process.Start(new ProcessStartInfo
{
FileName = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "osascript" : "notify-send",
Arguments = RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
? $"-e \"display notification \\\"Received {amountString} BTC\\\" with title \\\"Wasabi\\\"\""
: $"--expire-time=3000 \"Wasabi\" \"Received {amountString} BTC\"",
CreateNoWindow = true
}))
{ }
}
}
}
catch (Exception ex)
{
Logger.LogWarning(ex, nameof(Global));
}
}
public async Task DisposeInWalletDependentServicesAsync()
{
if (WalletService != null)
{
WalletService.Coins.CollectionChanged -= Coins_CollectionChanged;
}
try
{
_cancelWalletServiceInitialization?.Cancel();
}
catch (ObjectDisposedException)
{
Logger.LogWarning($"{nameof(_cancelWalletServiceInitialization)} is disposed. This can occur due to an error while processing the wallet.", nameof(Global));
}
_cancelWalletServiceInitialization = null;
if (WalletService != null)
{
if (WalletService.KeyManager != null) // This should not ever happen.
{
string backupWalletFilePath = Path.Combine(WalletBackupsDir, Path.GetFileName(WalletService.KeyManager.FilePath));
WalletService.KeyManager?.ToFile(backupWalletFilePath);
Logger.LogInfo($"{nameof(KeyManager)} backup saved to `{backupWalletFilePath}`.", nameof(Global));
}
if (WalletService != null)
{
await WalletService.StopAsync();
}
WalletService = null;
Logger.LogInfo($"{nameof(WalletService)} is stopped.", nameof(Global));
}
if (ChaumianClient != null)
{
await ChaumianClient.StopAsync();
ChaumianClient = null;
Logger.LogInfo($"{nameof(ChaumianClient)} is stopped.", nameof(Global));
}
}
/// <summary>
/// 0: nobody called
/// 1: somebody called
/// 2: call finished
/// </summary>
private long _dispose = 0; // To detect redundant calls
public async Task DisposeAsync()
{
var compareRes = Interlocked.CompareExchange(ref _dispose, 1, 0);
if (compareRes == 1)
{
while (Interlocked.Read(ref _dispose) != 2)
{
await Task.Delay(50);
}
return;
}
else if (compareRes == 2)
{
return;
}
try
{
await DisposeInWalletDependentServicesAsync();
if (UpdateChecker != null)
{
await UpdateChecker?.StopAsync();
Logger.LogInfo($"{nameof(UpdateChecker)} is stopped.", nameof(Global));
}
if (Synchronizer != null)
{
await Synchronizer?.StopAsync();
Logger.LogInfo($"{nameof(Synchronizer)} is stopped.", nameof(Global));
}
if (AddressManagerFilePath != null)
{
IoHelpers.EnsureContainingDirectoryExists(AddressManagerFilePath);
if (AddressManager != null)
{
AddressManager?.SavePeerFile(AddressManagerFilePath, Config.Network);
Logger.LogInfo($"{nameof(AddressManager)} is saved to `{AddressManagerFilePath}`.", nameof(Global));
}
}
if (Nodes != null)
{
Nodes?.Disconnect();
while (Nodes.ConnectedNodes.Any(x => x.IsConnected))
{
await Task.Delay(50);
}
Nodes?.Dispose();
Logger.LogInfo($"{nameof(Nodes)} are disposed.", nameof(Global));
}
if (RegTestMempoolServingNode != null)
{
RegTestMempoolServingNode.Disconnect();
Logger.LogInfo($"{nameof(RegTestMempoolServingNode)} is disposed.", nameof(Global));
}
if (TorManager != null)
{
await TorManager?.StopAsync();
Logger.LogInfo($"{nameof(TorManager)} is stopped.", nameof(Global));
}
if (AsyncMutex.IsAny)
{
try
{
await AsyncMutex.WaitForAllMutexToCloseAsync();
Logger.LogInfo($"{nameof(AsyncMutex)}(es) are stopped.", nameof(Global));
}
catch (Exception ex)
{
Logger.LogError($"Error during stopping {nameof(AsyncMutex)}: {ex}", nameof(Global));
}
}
}
catch (Exception ex)
{
Logger.LogWarning(ex, nameof(Global));
}
finally
{
Interlocked.Exchange(ref _dispose, 2);
}
}
public string GetNextWalletName()
{
for (int i = 0; i < int.MaxValue; i++)
{
if (!File.Exists(Path.Combine(WalletsDir, $"Wallet{i}.json")))
{
return $"Wallet{i}";
}
}
throw new NotSupportedException("This is impossible.");
}
public string GetNextHardwareWalletName(Hwi.Models.HardwareWalletInfo hwi = null, string customPrefix = null)
{
var prefix = customPrefix is null
? hwi is null
? "HardwareWallet"
: hwi.Type.ToString()
: customPrefix;
for (int i = 0; i < int.MaxValue; i++)
{
var name = $"{prefix}{i}";
if (!File.Exists(Path.Combine(WalletsDir, $"{name}.json")))
{
return name;
}
}
throw new NotSupportedException("This is impossible.");
}
}
}