Exemplo n.º 1
0
        private static Global CreateGlobal()
        {
            string dataDir = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Client"));

            Directory.CreateDirectory(dataDir);
            string torLogsFile = Path.Combine(dataDir, "TorLogs.txt");

            var uiConfig = new UiConfig(Path.Combine(dataDir, "UiConfig.json"));

            uiConfig.LoadOrCreateDefaultFile();
            var config = new Config(Path.Combine(dataDir, "Config.json"));

            config.LoadOrCreateDefaultFile();
            config.CorrectMixUntilAnonymitySet();
            var walletManager = new WalletManager(config.Network, dataDir, new WalletDirectories(config.Network, dataDir));

            return(new Global(dataDir, torLogsFile, config, uiConfig, walletManager));
        }
    /// <summary>
    /// Copies files one by one from <c>BlocksNETWORK_NAME</c> folder to <c>BitcoinStore/NETWORK_NAME/Blocks</c> if not already migrated.
    /// </summary>
    private void EnsureBackwardsCompatibility()
    {
        Logger.LogTrace(">");

        try
        {
            string   dataDir = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Client"));
            string   wrongGlobalBlockFolderPath = Path.Combine(dataDir, "Blocks");
            string[] wrongBlockFolderPaths      = new[]
            {
                // Before Wasabi 1.1.13
                Path.Combine(dataDir, $"Blocks{Network}"),
                Path.Combine(wrongGlobalBlockFolderPath, Network.Name)
            };

            foreach (string wrongBlockFolderPath in wrongBlockFolderPaths.Where(x => Directory.Exists(x)))
            {
                MigrateBlocks(wrongBlockFolderPath);
            }

            if (Directory.Exists(wrongGlobalBlockFolderPath))
            {
                // If all networks successfully migrated, too, then delete the transactions folder, too.
                if (!Directory.EnumerateFileSystemEntries(wrongGlobalBlockFolderPath).Any())
                {
                    Directory.Delete(wrongGlobalBlockFolderPath, recursive: true);
                    Logger.LogInfo($"Deleted '{wrongGlobalBlockFolderPath}' folder.");
                }
                else
                {
                    Logger.LogTrace($"Cannot delete '{wrongGlobalBlockFolderPath}' folder as it is not empty.");
                }
            }
        }
        catch (Exception ex)
        {
            Logger.LogWarning("Backwards compatibility could not be ensured.");
            Logger.LogWarning(ex);
        }

        Logger.LogTrace("<");
    }
Exemplo n.º 3
0
 public Global(string dataDir)
 {
     DataDir = dataDir ?? EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Backend"));
 }
Exemplo n.º 4
0
 public string Get()
 {
     return(EnvironmentHelpers.GetDataDir(Path.Combine("Test", "Client")));
 }
Exemplo n.º 5
0
 public Global()
 {
     DataDir = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Backend"));
 }
Exemplo n.º 6
0
 static Global()
 {
     SetDataDir(EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Client")));
 }
Exemplo n.º 7
0
        // Initialization code. Don't use any Avalonia, third-party APIs or any
        // SynchronizationContext-reliant code before AppMain is called: things aren't initialized
        // yet and stuff might break.
        public static int Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            TaskScheduler.UnobservedTaskException      += TaskScheduler_UnobservedTaskException;
            bool runGui = true;

            try
            {
                if (CrashReporter.TryGetExceptionFromCliArgs(args, out var exceptionToShow))
                {
                    // Show the exception.
                    Console.WriteLine($"TODO Implement crash reporting. {exceptionToShow}");

                    runGui = false;
                }
            }
            catch (Exception ex)
            {
                // Anything happens here just log it and do not run the Gui.
                Logger.LogCritical(ex);
                runGui = false;
            }

            Exception?            exceptionToReport     = null;
            SingleInstanceChecker?singleInstanceChecker = null;

            if (runGui)
            {
                try
                {
                    string dataDir = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Client"));

                    SetupLogger(dataDir, args);
                    var(uiConfig, config) = LoadOrCreateConfigs(dataDir);

                    singleInstanceChecker = new SingleInstanceChecker(config.Network);
                    singleInstanceChecker.EnsureSingleOrThrowAsync().GetAwaiter().GetResult();

                    Global = CreateGlobal(dataDir, uiConfig, config);

                    // TODO only required due to statusbar vm... to be removed.
                    Locator.CurrentMutable.RegisterConstant(Global);

                    Logger.LogSoftwareStarted("Wasabi GUI");
                    BuildAvaloniaApp(Global)
                    .AfterSetup(_ => ThemeHelper.ApplyTheme(Global.UiConfig.DarkModeEnabled))
                    .StartWithClassicDesktopLifetime(args);
                }
                catch (OperationCanceledException ex)
                {
                    Logger.LogDebug(ex);
                }
                catch (Exception ex)
                {
                    exceptionToReport = ex;
                    Logger.LogCritical(ex);
                }
            }

            // Start termination/disposal of the application.

            TerminateService.Terminate();

            if (singleInstanceChecker is { } single)
            {
                Task.Run(async() => await single.DisposeAsync()).Wait();
            }

            if (exceptionToReport is { })
Exemplo n.º 8
0
        private volatile bool _disposedValue = false;         // To detect redundant calls

        public RegTestFixture()
        {
            RuntimeParams.SetDataDir(Path.Combine(Common.DataDir, "RegTests", "Backend"));
            RuntimeParams.LoadAsync().GetAwaiter().GetResult();
            var hostedServices = new HostedServices();

            BackendRegTestNode = TestNodeBuilder.CreateAsync(hostedServices, callerFilePath: "RegTests", callerMemberName: "BitcoinCoreData").GetAwaiter().GetResult();

            var walletName = "wallet.dat";

            BackendRegTestNode.RpcClient.CreateWalletAsync(walletName).GetAwaiter().GetResult();

            var testnetBackendDir = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Tests", "RegTests", "Backend"));

            IoHelpers.TryDeleteDirectoryAsync(testnetBackendDir).GetAwaiter().GetResult();
            Thread.Sleep(100);
            Directory.CreateDirectory(testnetBackendDir);
            Thread.Sleep(100);
            var config = new Config(
                BackendRegTestNode.RpcClient.Network,
                BackendRegTestNode.RpcClient.CredentialString.ToString(),
                new IPEndPoint(IPAddress.Loopback, Network.Main.DefaultPort),
                new IPEndPoint(IPAddress.Loopback, Network.TestNet.DefaultPort),
                BackendRegTestNode.P2pEndPoint,
                new IPEndPoint(IPAddress.Loopback, Network.Main.RPCPort),
                new IPEndPoint(IPAddress.Loopback, Network.TestNet.RPCPort),
                BackendRegTestNode.RpcEndPoint);
            var configFilePath = Path.Combine(testnetBackendDir, "Config.json");

            config.SetFilePath(configFilePath);
            config.ToFile();

            var roundConfig         = CreateRoundConfig(Money.Coins(0.1m), Constants.OneDayConfirmationTarget, 0.7, 0.1m, 100, 120, 60, 60, 60, 1, 24, true, 11);
            var roundConfigFilePath = Path.Combine(testnetBackendDir, "CcjRoundConfig.json");

            roundConfig.SetFilePath(roundConfigFilePath);
            roundConfig.ToFile();

            var conf = new ConfigurationBuilder()
                       .AddInMemoryCollection(new[] { new KeyValuePair <string, string>("datadir", testnetBackendDir) })
                       .Build();

            BackendEndPoint       = $"http://localhost:{CryptoHelpers.RandomInt(37130, 37999)}/";
            BackendEndPointUri    = new Uri(BackendEndPoint);
            BackendEndPointApiUri = new Uri(BackendEndPointUri, $"/api/v{Constants.BackendMajorVersion}/");

            BackendHost = Host.CreateDefaultBuilder()
                          .ConfigureWebHostDefaults(webBuilder => webBuilder
                                                    .UseStartup <Startup>()
                                                    .UseConfiguration(conf)
                                                    .UseWebRoot("../../../../WalletWasabi.Backend/wwwroot")
                                                    .UseUrls(BackendEndPoint))
                          .Build();

            if (BackendHost.Services.GetService(typeof(Global)) is not Global global)
            {
                throw new InvalidOperationException($"Service {nameof(Global)} is not registered.");
            }

            Global = global;
            Global.HostedServices = hostedServices;
            var hostInitializationTask = BackendHost.RunWithTasksAsync();

            Logger.LogInfo($"Started Backend webhost: {BackendEndPoint}");

            HttpClient        = new HttpClient();
            BackendHttpClient = new ClearnetHttpClient(HttpClient, () => BackendEndPointUri);

            var delayTask = Task.Delay(3000);

            Task.WaitAny(delayTask, hostInitializationTask);             // Wait for server to initialize (Without this OSX CI will fail)
        }
Exemplo n.º 9
0
    // Initialization code. Don't use any Avalonia, third-party APIs or any
    // SynchronizationContext-reliant code before AppMain is called: things aren't initialized
    // yet and stuff might break.
    public static int Main(string[] args)
    {
        bool runGuiInBackground = args.Any(arg => arg.Contains(StartupHelper.SilentArgument));

        // Initialize the logger.
        string dataDir = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Client"));

        SetupLogger(dataDir, args);

        Logger.LogDebug($"Wasabi was started with these argument(s): {(args.Any() ? string.Join(" ", args) : "none") }.");

        // Crash reporting must be before the "single instance checking".
        try
        {
            if (CrashReporter.TryGetExceptionFromCliArgs(args, out var exceptionToShow))
            {
                // Show the exception.
                BuildCrashReporterApp(exceptionToShow).StartWithClassicDesktopLifetime(args);
                return(1);
            }
        }
        catch (Exception ex)
        {
            // If anything happens here just log it and exit.
            Logger.LogCritical(ex);
            return(1);
        }

        (UiConfig uiConfig, Config config) = LoadOrCreateConfigs(dataDir);

        // Start single instance checker that is active over the lifetime of the application.
        using SingleInstanceChecker singleInstanceChecker = new(config.Network);

        try
        {
            singleInstanceChecker.EnsureSingleOrThrowAsync().GetAwaiter().GetResult();
        }
        catch (OperationCanceledException)
        {
            // We have successfully signalled the other instance and that instance should pop up
            // so user will think he has just run the application.
            return(1);
        }
        catch (Exception ex)
        {
            CrashReporter.Invoke(ex);
            Logger.LogCritical(ex);
            return(1);
        }

        // Now run the GUI application.
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        TaskScheduler.UnobservedTaskException      += TaskScheduler_UnobservedTaskException;

        Exception?       exceptionToReport = null;
        TerminateService terminateService  = new(TerminateApplicationAsync, TerminateApplication);

        try
        {
            Global = CreateGlobal(dataDir, uiConfig, config);
            Services.Initialize(Global, singleInstanceChecker);

            Logger.LogSoftwareStarted("Wasabi GUI");
            AppBuilder
            .Configure(() => new App(async() => await Global.InitializeNoWalletAsync(terminateService), runGuiInBackground)).UseReactiveUI()
            .SetupAppBuilder()
            .AfterSetup(_ =>
            {
                var glInterface = AvaloniaLocator.CurrentMutable.GetService <IPlatformOpenGlInterface>();
                Logger.LogInfo(glInterface is { }
                                                        ? $"Renderer: {glInterface.PrimaryContext.GlInterface.Renderer}"
                                                        : "Renderer: Avalonia Software");

                ThemeHelper.ApplyTheme(Global.UiConfig.DarkModeEnabled ? Theme.Dark : Theme.Light);
            })
            .StartWithClassicDesktopLifetime(args);
        }
Exemplo n.º 10
0
 public Global(string dataDir)
 {
     DataDir        = dataDir ?? EnvironmentHelpers.GetDataDir(Path.Combine("MustardWalletLTC", "Backend"));
     HostedServices = new HostedServices();
 }